Skip to content

Commit 1d03761

Browse files
committed
2 problems
1 parent e14c84d commit 1d03761

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
208208
#### [279. Perfect Squares](https://github.com/hitzzc/go-leetcode/tree/master/perfect_squares)
209209
#### [282. Expression Add Operators](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators)
210210
#### [283. Move Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators)
211+
#### [284. Peeking Iterator](https://github.com/hitzzc/go-leetcode/tree/master/peeking_iterator)
212+
#### [287. Find the Duplicate Number](https://github.com/hitzzc/go-leetcode/tree/master/find_the_duplicate_number)
211213

212214

213215

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
int findDuplicate(vector<int>& nums) {
4+
int i = 0;
5+
int j = 0;
6+
while (true) {
7+
i = nums[i];
8+
j = nums[nums[j]];
9+
if (i == j) break;
10+
}
11+
j = 0;
12+
while (i != j) {
13+
i = nums[i];
14+
j = nums[j];
15+
}
16+
return i;
17+
}
18+
};

peeking_iterator/peeking_iterator.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Below is the interface for Iterator, which is already defined for you.
2+
// **DO NOT** modify the interface for Iterator.
3+
class Iterator {
4+
struct Data;
5+
Data* data;
6+
public:
7+
Iterator(const vector<int>& nums);
8+
Iterator(const Iterator& iter);
9+
virtual ~Iterator();
10+
// Returns the next element in the iteration.
11+
int next();
12+
// Returns true if the iteration has more elements.
13+
bool hasNext() const;
14+
};
15+
16+
17+
class PeekingIterator : public Iterator {
18+
int cache;
19+
bool is_peeked;
20+
public:
21+
PeekingIterator(const vector<int>& nums) : Iterator(nums), is_peeked(false) {
22+
23+
}
24+
25+
// Returns the next element in the iteration without advancing the iterator.
26+
int peek() {
27+
if (!is_peeked) {
28+
cache = Iterator::next();
29+
is_peeked = true;
30+
}
31+
return cache;
32+
}
33+
34+
// hasNext() and next() should behave the same as in the Iterator interface.
35+
// Override them if needed.
36+
int next() {
37+
if (is_peeked) {
38+
is_peeked = false;
39+
return cache;
40+
}
41+
return Iterator::next();
42+
}
43+
44+
bool hasNext() const {
45+
if (is_peeked) {
46+
return true;
47+
}
48+
return Iterator::hasNext();
49+
}
50+
};

0 commit comments

Comments
 (0)