KK's blog

每天积累多一些

0%

LeetCode



Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

Vector2D(int[][] vec) initializes the object with the 2D vector vec. next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
hasNext() returns true if there are still some elements in the vector, and false otherwise.

Example 1:

Input
[“Vector2D”, “next”, “next”, “next”, “hasNext”, “hasNext”, “next”, “hasNext”]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
Output
[null, 1, 2, 3, true, true, 4, false]

Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next(); // return 1
vector2D.next(); // return 2
vector2D.next(); // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next(); // return 4
vector2D.hasNext(); // return False


Constraints:
0 <= vec.length <= 200
0 <= vec[i].length <= 500 -500 <= vec[i][j] <= 500
At most 10<sup>5</sup> calls will be made to next and hasNext.

*Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

题目大意:

实现二维Vector的Iterator

解题思路:

用两个指针

解题步骤:

N/A

注意事项:

  1. 单一Vector可以是空,所以next要循环找到非空的vector
  2. next要col_id加一

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Vector2D(TestCases):

def __init__(self, vec: List[List[int]]):
self.vec = vec
self.row_id = 0
self.col_id = 0

def next(self) -> int:
if self.hasNext():
val = self.vec[self.row_id][self.col_id]
self.col_id += 1 # remember
return val
return None

def hasNext(self) -> bool:
while self.row_id < len(self.vec) and self.col_id == len(self.vec[self.row_id]): # remember while coz []
self.row_id += 1
self.col_id = 0
if self.row_id == len(self.vec):
return False
else:
return True

算法分析:

每个操作时间复杂度为O(V/N)O(1),空间复杂度O(1), N为所有数,V为vector数,O(N + V)/N. O(1)如果vector都不会空

LeetCode 272 Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:

  • Given target value is a floating point.
  • You may assume k is always valid, that is: k≤ total nodes.
  • You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Example:

Input: root = [4,2,5,1,3], target = 3.714286, and _k_ = 2

    4
   / \
  2   5
 / \
1   3

Output: [4,3]

Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

题目大意:

找BST中给定目标的最接近的k个值。

解题思路:

首先观察得到最接近的节点一定在二叉树的搜索路径上的节点的其中一个。这样可以分成两组
前驱节点和后驱节点(比target大),加入到两个stack中,由BST的iterator可以知道这两个
stack的越靠近栈首就越接近target,所以出栈的一定是最接近target的。只要比较两栈首元素
即可。如果某个节点出栈要找其儿子节点填充。找前驱节点和后驱节点的方法是相反的。这里可
参照KB的BST非递归中序遍历。

注意事项:

  1. 找最接近target的节点,不用判断左右儿子是否为空,因为若为空,表示root更接近。大于target的放入successors,否则是predecessors
  2. 然后判断两栈首谁大,谁大的就获得相应的比它远离target的节点入栈。如predecessors是左节点的所有右儿子。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
predecessors, successors = [], []
it = root
while it:
if target < it.val:
successors.append(it)
it = it.left
else:
predecessors.append(it)
it = it.right
res = []
while k > 0:
if predecessors and (not successors or target - predecessors[-1].val < successors[-1].val - target):
node = predecessors.pop()
if node.left:
n = node.left
while n:
predecessors.append(n)
n = n.right
res.append(node.val)
else:
node = successors.pop()
if node.right:
n = node.right
while n:
successors.append(n)
n = n.left
res.append(node.val)
k -= 1
return res

注意事项:

  1. target - preOrder.peek().val < postOrder.peek().val - target的条件前
    记得加上!preOrder.isEmpty()

Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public List<Integer> closestKValues(TreeNode root, double target, int k) {
List<Integer> res = new ArrayList<>();
if(root == null)
return res;
Stack<TreeNode> preOrder = new Stack<>();
Stack<TreeNode> postOrder = new Stack<>();
findTargetAndPopulateStacks(preOrder, postOrder, root, target);

while(k-- > 0) {
if(postOrder.isEmpty() || (!preOrder.isEmpty() &&
target - preOrder.peek().val < postOrder.peek().val - target))
getPredecessor(preOrder, res);
else
getSuccessor(postOrder, res);
}
return res;
}

void findTargetAndPopulateStacks(Stack<TreeNode> preOrder, Stack<TreeNode> postOrder,
TreeNode root, double target) {
TreeNode node = root;
while(node != null) {
if(node.val < target) {
preOrder.push(node);
node = node.right;
}
else {
postOrder.push(node);
node = node.left;
}
}
}

void getSuccessor(Stack<TreeNode> postOrder, List<Integer> res) {
TreeNode node = postOrder.pop();
res.add(node.val);
if(node.right != null) {
TreeNode n = node.right;
while(n != null) {
postOrder.push(n);
n = n.left;
}
}
}

void getPredecessor(Stack<TreeNode> preOrder, List<Integer> res) {
TreeNode node = preOrder.pop();
res.add(node.val);
if(node.left != null) {
TreeNode n = node.left;
while(n != null) {
preOrder.push(n);
n = n.right;
}
}
}

算法分析:

时间复杂度为O(k + logn),空间复杂度O(logn)。

LeetCode



Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator. int next() Returns the next element in the array and moves the pointer to the next element.
boolean hasNext() Returns true if there are still elements in the array. int peek() Returns the next element in the array without moving the pointer.

Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

Example 1:

Input
[“PeekingIterator”, “next”, “peek”, “next”, “next”, “hasNext”]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False


Constraints:

1 <= nums.length <= 1000 1 <= nums[i] <= 1000
All the calls to next and peek are valid. At most 1000 calls will be made to next, hasNext, and peek.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

题目大意:

实现数组的peeking Iterator。数组的Iterator是给定的。

解题思路:

预读一个数

解题步骤:

N/A

注意事项:

  1. 预读一个next数

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class PeekingIterator(TestCases):

def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
if self.iterator.hasNext():
self.num = self.iterator.next()
else:
self.num = None

def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.num

def next(self):
"""
:rtype: int
"""
tmp = self.num
if self.iterator.hasNext():
self.num = self.iterator.next()
else:
self.num = None
return tmp

def hasNext(self):
"""
:rtype: bool
"""
return self.num is not None

算法分析:

时间复杂度为O(1),空间复杂度O(1)

LeetCode



You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:



Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]


Example 2:



Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]


Constraints:

n == matrix.length == matrix[i].length 1 <= n <= 20
* -1000 <= matrix[i][j] <= 1000

题目大意:

顺时针循环矩阵90度

解题思路:

先上下对称,再沿正对角线(左上到右下)对称。正对角线实现比较容易

解题步骤:

N/A

注意事项:

  1. 先上下对称,再沿正对角线(左上到右下)对称。正对角线实现比较容易

Python代码:

1
2
3
4
5
6
7
8
def rotate(self, matrix: List[List[int]]) -> None:
for i in range(len(matrix) // 2):
for j in range(len(matrix[0])):
matrix[i][j], matrix[len(matrix) - 1 - i][j] = matrix[len(matrix) - 1 - i][j], matrix[i][j]

for i in range(len(matrix)):
for j in range(i, len(matrix[0])):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

算法分析:

时间复杂度为O(n2),空间复杂度O(1)

LeetCode



Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library’s sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]


Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]


Constraints:

n == nums.length 1 <= n <= 300
nums[i] is either 0, 1, or 2.

*Follow up:
Could you come up with a one-pass algorithm using only constant extra space?

题目大意:

排序3值数组

算法思路:

类似于Quicksort的partition,但有三种值,需要有三个指针: left, i, right

注意事项:

  1. 三个指针: left, i, right. 循环不是for每个元素,而是i <= right
  2. nums[2]的时候,right要往前移
  3. 和partition一样: nums[i] == 0,left和i都移动,nums[i] == 1只移动i

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
def sortColors(self, nums: List[int]) -> None:
left, i, right = 0, 0, len(nums) - 1
while i <= right: # remember
if nums[i] == 0:
nums[left], nums[i] = nums[i], nums[left]
left += 1
i += 1
elif nums[i] == 1:
i += 1
else:
nums[i], nums[right] = nums[right], nums[i]
right -= 1 # remember

Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void sortColors(int[] nums) {
int middleStart = 0, middleEnd = nums.length-1, i=0;
while(i<=middleEnd){
if(nums[i]==2)
swap(nums,i,middleEnd--);//no i++ coz 2,0,2,2, swap 2,2 and i can't +1
else if(nums[i]==0)
swap(nums,i++,middleStart++);
else
i++;
}

}

public void swap(int[] a,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview