当前位置:   article > 正文

面试笔试杂项积累-leetcode 221-225_simluatechainnode

simluatechainnode

221.221-Combination Sum III-Difficulty: Medium

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.

思路

最大全1正方形面积

用动态规划求出最大边长,再平方

以当前点(x,y) = '1' 为右下角的最大正方形的边长f(x,y) = min( f(x-1,y), f(x,y-1), f(x-1,y-1)) + 1.

  1. public class Solution {
  2. public int MaximalSquare(char[,] matrix) {
  3. if (matrix == null || matrix.Length == 0) return 0;
  4. int row = matrix.GetLength(0);
  5. int col = matrix.GetLength(1);
  6. int max = 0;
  7. int[,] temp = new int[row, col];
  8. for (int i = 0; i < row; i++)
  9. for (int j = 0; j < col; j++)
  10. if (matrix[i, j] == '1')
  11. { temp[i, j] = 1;max = 1;}
  12. for (int i = 1; i < row; i++)
  13. for (int j = 1; j < col; j++)
  14. {
  15. if (matrix[i, j] == '1')
  16. {
  17. temp[i, j] = Math.Min(Math.Min(temp[i - 1, j], temp[i, j - 1]), temp[i - 1, j - 1]) + 1;//求出最长边长
  18. max = Math.Max(max, temp[i, j]);
  19. }
  20. }
  21. return max*max;
  22. }
  23. }

222.222-Count Complete Tree Nodes-Difficulty: Medium

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

方法一

思路

给予一个完全二叉树,返回所有节点个数

用先序中序后序都是超时的

要利用完全二叉树这个所给条件

参考:

https://leetcode.com/discuss/73892/a-very-clear-recursive-solution-isnt-it

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int count = 0;
  12. public int CountNodes(TreeNode root) {
  13. if (root == null) return 0;
  14. int lh = fTreeHt(root.left);
  15. int rh = fTreeHt(root.right);
  16. if (lh == rh)
  17. return (1 << lh) + CountNodes(root.right); /*1(根节点) + (1<<lh)-1(完全左子树) + # of rightNode */
  18. else
  19. return (1 << rh) + CountNodes(root.left); /*1(根节点) + (1<<rh)-1(完全右子树) + # of leftNode*/
  20. }
  21. int fTreeHt(TreeNode root)
  22. { //get the height of a complete binary tree.
  23. if (root == null) return 0;
  24. return 1 + fTreeHt(root.left);
  25. }
  26. }

方法二

思路

  1. public class Solution {
  2. public int countNodes(TreeNode root) {
  3. return root == null ? 0 : findLastIndex(root, 1);
  4. }
  5. private int lHeight(TreeNode node, int count) {
  6. return node == null ? count - 1 : lHeight(node.left, count + 1);
  7. }
  8. private int findLastIndex(TreeNode node, int currIndex) {
  9. if (node.left == null && node.right == null) return currIndex;
  10. if (lHeight(node.left, 1) == lHeight(node.right, 1))
  11. return findLastIndex(node.right, currIndex * 2 + 1);
  12. else return findLastIndex(node.left, currIndex * 2);
  13. }
  14. }

Before understanding my solution, I'm gonna explain what does "index" mean in this solution.

If we mark the tree nodes from left to right, top to bottom with increasing integers, starting with 1, then let's call this number "Index". There are some properties of it:
(1) The largest index is the answer we want. It equals to the number of nodes.
(2) Since it's complete binary tree, for a node with index x, the left child, if exist, has index 2 * x. The right child, if exist, has index 2 * x + 1.

So in this solution, I'm trying to "walk" to the node with largest index starting from the root, which has index 1. Let's denote the height of left child tree is lH, the height of right child tree is rH:
(1) if lH == rH, meaning left child tree is a full tree, the last node must be in the right child tree. So we move to the right child node.
(2) Otherwise, the last node must be in the left child tree, so we move to the left.

So by "tracing" the node with largest index, we can find the answer.

Time complexity:
Because the total number of steps equals to the height of the tree h, at each step, calculating the height will cost time O(h - current step) so the time complexity is h + (h - 1) + (h - 2) + ... + 1 = O(h^2) = O(log(n)^2).


223.223-Rectangle Area-Difficulty: Easy

Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

思路

求出上图面积

注意二矩形位置和大小不定,有可能有一矩形面积为0,也有可能丝毫不相交,也有可能位置互换等

此时的关键就是求出中间小矩形的面积

  1. public class Solution {
  2. public int ComputeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
  3. int overlap = 0;
  4. int minx = A < E ? E : A;
  5. int maxx = C < G ? C : G;
  6. int miny = F < B ? B : F;
  7. int maxy = H < D ? H : D;
  8. if (minx > maxx || miny > maxy)
  9. overlap = 0;
  10. else
  11. overlap = (maxy - miny) * (maxx - minx);
  12. return (C - A) * (D - B) + (G - E) * (H - F) -overlap;
  13. }
  14. }

224.224-Basic Calculator-Difficulty: Medium

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

思路

给出string算式求出结果,包括+,-和括号

遇到 '(' 就把之前的结果和符号push进stack. 遇到')'就把 当前结果*stack中的符号 再加上stack中之前的结果.

+,-当做+1,-1与当前数值求积即可

  1. public class Solution {
  2. public int Calculate(string s) {
  3. s = s.Trim(' ');
  4. Stack<int> stack = new Stack<int>();
  5. int res = 0;
  6. int sign = 1;
  7. for (int i = 0; i < s.Length; i++)
  8. {
  9. if (char.IsDigit(s[i]))
  10. {
  11. int temp = s[i] - '0';
  12. while (i < s.Length - 1 && char.IsDigit(s[i + 1]))
  13. {
  14. temp = temp * 10 + s[i + 1] - '0';
  15. ++i;
  16. }
  17. res = res + sign * temp;
  18. }
  19. else if (s[i] == '+')
  20. {
  21. sign = 1;
  22. }
  23. else if (s[i] == '-')
  24. {
  25. sign = -1;
  26. }
  27. else if (s[i] == '(')
  28. {
  29. stack.Push(res);
  30. stack.Push(sign);
  31. res = 0;
  32. sign = 1;
  33. }
  34. else if (s[i] == ')')
  35. {
  36. res = res * stack.Pop()+stack.Pop();
  37. sign = 1;
  38. }
  39. }
  40. return res;
  41. }
  42. }

225.225- Implement Stack using Queues-Difficulty: Easy

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

方法一

思路

使用队列实现栈的操作,

博主开始没注意是使用队列,就用链表实现了= =。。。这个方法先放这

  1. public class Stack {
  2. class ChainNode
  3. {
  4. public int val;
  5. public ChainNode next;
  6. public ChainNode(int _val)
  7. {
  8. this.val = _val;
  9. }
  10. }
  11. ChainNode head;
  12. int size = 0;
  13. // Push element x onto stack.
  14. public void Push(int x)
  15. {
  16. ChainNode temp = head;
  17. head = new ChainNode(x);
  18. head.next = temp;
  19. ++size;
  20. }
  21. // Removes the element on top of the stack.
  22. public void Pop()
  23. {
  24. head = head.next;
  25. --size;
  26. }
  27. // Get the top element.
  28. public int Top()
  29. {
  30. return head.val;
  31. }
  32. // Return whether the stack is empty.
  33. public bool Empty()
  34. {
  35. return size <= 0;
  36. }
  37. }

方法二

思路

使用一个队列实现

众所周知,栈和队列的不同一个是先入后出,一个是先入先出,

我们完全可以在push的时候调一下位置使队列的位置满足栈的位置即可,剩下的操作就都用队列的就可以了

  1. class MyStack {
  2. //one Queue solution
  3. private Queue<Integer> q = new LinkedList<Integer>();
  4. // Push element x onto stack.
  5. public void push(int x) {
  6. q.add(x);
  7. for(int i = 1; i < q.size(); i ++) { //rotate the queue to make the tail be the head
  8. q.add(q.poll());
  9. }
  10. }
  11. // Removes the element on top of the stack.
  12. public void pop() {
  13. q.poll();
  14. }
  15. // Get the top element.
  16. public int top() {
  17. return q.peek();
  18. }
  19. // Return whether the stack is empty.
  20. public boolean empty() {
  21. return q.isEmpty();
  22. }

方法三

思路

使用两个队列实现

也是在push中进行操作,两个队列来回颠倒,使其中一个有栈的顺序,其中一个为空

参考:

https://leetcode.com/discuss/84233/solutions-about-which-utilizes-queue-others-utilize-queues


1 Push method is inefficient.

when you push an element, choose one empty queue(whichever when both are empty) to add this element, and then push all elements of the other queue into the chosen queue. After that, the newest element is at the head of the chosen queue so that whenever you want to do pop() or top(), you always get the newest element.

For example,

push(1):

[ , ,1] [ , , ]

push(2):

[ , , ] [ ,1,2]

push(3):

[ 1, 2,3 ] [ , , ]

  1. class MyStack {
  2. //using two queue. The push is inefficient.
  3. private Queue<Integer> q1 = new LinkedList<Integer>();
  4. private Queue<Integer> q2 = new LinkedList<Integer>();
  5. public void push(int x) {
  6. if(q1.isEmpty()) {
  7. q1.add(x);
  8. for(int i = 0; i < q2.size(); i ++)
  9. q1.add(q2.poll());
  10. }else {
  11. q2.add(x);
  12. for(int i = 0; i < q1.size(); i++)
  13. q2.add(q1.poll());
  14. }
  15. }
  16. public void pop() {
  17. if(!q1.isEmpty())
  18. q1.poll();
  19. else
  20. q2.poll();
  21. }
  22. public int top() {
  23. return q1.isEmpty() ? q2.peek() : q1.peek();
  24. }
  25. public boolean empty() {
  26. return q1.isEmpty() && q2.isEmpty();
  27. }
  28. }

方法四

思路

两个队列,在其他操作中颠倒顺序,不在push中

参考:

https://leetcode.com/discuss/84233/solutions-about-which-utilizes-queue-others-utilize-queues

2 pop() and top() are inefficient

When you push elements, choose a queue which is not empty(whichever when both are empty).When you do pop() or top(), first pop all elements of the queue except the tail into another empty queue, and then pop the tail which is your want.

For example:

push(1):

[ , , 1] [ , , ]

push(2):

[ ,2,1] [ , , ]

top();

[ , , 2] [ , ,1] -> [ , , ] [ ,2,1]

pop():

[ , , 1] [ , ,2] -> [ , ,1] [ , , ]

push(3) :

[ ,3,1] [ , , ]

  1. class MyStack{
  2. //using two queue. The pop and top are inefficient.
  3. private Queue<Integer> q1 = new LinkedList<Integer>();
  4. private Queue<Integer> q2 = new LinkedList<Integer>();
  5. public void push(int x) {
  6. if(!q1.isEmpty())
  7. q1.add(x);
  8. else
  9. q2.add(x);
  10. }
  11. public void pop() {
  12. if(q1.isEmpty()) {
  13. int size = q2.size();
  14. for(int i = 1; i < size; i ++) {
  15. q1.add(q2.poll());
  16. }
  17. q2.poll();
  18. }else {
  19. int size = q1.size();
  20. for(int i = 1; i < size; i ++) {
  21. q2.add(q1.poll());
  22. }
  23. q1.poll();
  24. }
  25. }
  26. public int top() {
  27. int res;
  28. if(q1.isEmpty()) {
  29. int size = q2.size();
  30. for(int i = 1; i < size; i ++) {
  31. q1.add(q2.poll());
  32. }
  33. res = q2.poll();
  34. q1.add(res);
  35. }else {
  36. int size = q1.size();
  37. for(int i = 1; i < size; i ++) {
  38. q2.add(q1.poll());
  39. }
  40. res = q1.poll();
  41. q2.add(res);
  42. }
  43. return res;
  44. }
  45. public boolean empty() {
  46. return q1.isEmpty() && q2.isEmpty();
  47. }
  48. }











声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/718935
推荐阅读
相关标签
  

闽ICP备14008679号