KK's blog

每天积累多一些

0%

LeetCode



Given two vectors of integers v1 and v2, implement an iterator to return their elements alternately.

Implement the ZigzagIterator class:

ZigzagIterator(List<int> v1, List<int> v2) initializes the object with the two vectors v1 and v2. boolean hasNext() returns true if the iterator still has elements, and false otherwise.
int next() returns the current element of the iterator and moves the iterator to the next element.

Example 1:

Input: v1 = [1,2], v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6].


Example 2:

Input: v1 = [1], v2 = []
Output: [1]


Example 3:

Input: v1 = [], v2 = [1]
Output: [1]


Constraints:
0 <= v1.length, v2.length <= 1000
1 <= v1.length + v2.length <= 2000 -2<sup>31</sup> <= v1[i], v2[i] <= 2<sup>31</sup> - 1

Follow up: What if you are given k vectors? How well can your code be extended to such cases?

Clarification for the follow-up question:

The “Zigzag” order is not clearly defined and is ambiguous for k > 2 cases. If “Zigzag” does not look right to you, replace “Zigzag” with “Cyclic”.

Follow-up Example:

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


题目大意:

求两数组轮替取值的Iterator

解题思路:

将数组和数组下标分别存于新数组中。用一个list_index来记录要取哪个数组

解题步骤:

N/A

注意事项:

  1. 用Iterator模板,hasNext也是找到下一个元素为止,由于只有两个数组,所以不用循环。取值是一个二维数组val = self.input[self.list_index][self.index[self.list_index]]
  2. next中取值后指针要后移。

Python代码:

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

def __init__(self, v1: List[int], v2: List[int]):
self.input = [v1, v2]
self.index = [0, 0]
self.list_index = 0

def next(self) -> int:
if self.hasNext():
val = self.input[self.list_index][self.index[self.list_index]]
self.index[self.list_index] += 1
self.list_index = (self.list_index + 1) % 2
return val
return None

def hasNext(self) -> bool:
if self.index[self.list_index] < len(self.input[self.list_index]):
return True
self.list_index = (self.list_index + 1) % 2
return self.index[self.list_index] < len(self.input[self.list_index])

算法分析:

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

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)

算法思路:

hasNext, next都涉及计算下一个元素,大部分题目是先计算再返回。只有BST是先返回再计算,因为BST的下一个节点取决于要返回的节点,若返回了,就无法知道下一个节点。

注意事项:

  1. hasNext中,while循环找到下一个符合条件的元素
  2. next中取值后指针要后移

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
def __init__(self):
self.stack = []
<add to stack>

def next(self) -> int:
if self.hasNext():
return self.stack.pop()
return None

def hasNext(self) -> bool:
while <until find the next element>:
<calculate>
return <next element>

应用题型:

LeetCode 251 Flatten 2D Vector
LeetCode 281 Zigzag Iterator
LeetCode 341 Flatten Nested List Iterator
LeetCode 173 Binary Search Tree Iterator

算法分析:

next操作时间复杂度为O(N + V)/NO(1),N为所有数,V为复合结构数

LeetCode



You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next() Returns the next integer in the nested list.
boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following pseudocode:

initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res


If res matches the expected flattened list, then your code will be judged as correct.

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].


Example 2:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].


Constraints:
1 <= nestedList.length <= 500
* The values of the integers in the nested list is in the range [-10<sup>6</sup>, 10<sup>6</sup>].

题目大意:

实现Nested List的Iterator。Nested List是NestedInteger的数组,NestedInteger可以是int,也可以是Nested List

解题思路:

有点似括号题但区别是从前往后读取。用Queue或Stack都可以,插入或删除其一需要反序,删除nestedinteger(=list)后要将它里面所有nestedinteger加入。Queue要从队首加入和删除,Stack要从栈顶加入和删除,用Stack比较方便。

Nested List题目:
LeetCode 341 Flatten Nested List Iterator Iterator - Stack
LeetCode 339 Nested List Weight Sum - BFS
LeetCode 364 Nested List Weight Sum II - BFS

解题步骤:

N/A

注意事项:

  1. 用Stack,逆序将nestedList中nestedinteger加入到stack,直到栈顶元素为int,hasNext才算结束

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class NestedIterator(TestCases):

def __init__(self, nestedList):
self.stack = []
for i in reversed(range(len(nestedList))):
self.stack.append(nestedList[i])

def next(self) -> int:
if self.hasNext():
return self.stack.pop().getInteger()
return None

def hasNext(self) -> bool:
while self.stack and not self.stack[-1].isInteger():
nestedList = self.stack.pop().getList()
for i in reversed(range(len(nestedList))):
self.stack.append(nestedList[i])
return True if self.stack else False

算法分析:

next操作时间复杂度为O(V/N)O(1),空间复杂度O(L + N), N为所有数,V为nested list数,O(N + V)/N. O(1)如果不存在nested list

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都不会空

Free mock interview