Skip to content

Commit b230113

Browse files
authored
Added tasks 284, 287, 289, 290.
1 parent 4236274 commit b230113

File tree

12 files changed

+382
-0
lines changed

12 files changed

+382
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package g0201_0300.s0284_peeking_iterator;
2+
3+
import java.util.Iterator;
4+
5+
public class PeekingIterator implements Iterator<Integer> {
6+
Iterator<Integer> it;
7+
Integer current;
8+
9+
public PeekingIterator(Iterator<Integer> iterator) {
10+
// initialize any member here.
11+
it = iterator;
12+
current = it.next();
13+
}
14+
15+
// Returns the next element in the iteration without advancing the iterator.
16+
public Integer peek() {
17+
if (current == null) {
18+
current = it.next();
19+
}
20+
return current;
21+
}
22+
23+
// hasNext() and next() should behave the same as in the Iterator interface.
24+
// Override them if needed.
25+
@Override
26+
public Integer next() {
27+
Integer temp = current;
28+
current = it.hasNext() ? it.next() : null;
29+
return temp;
30+
}
31+
32+
@Override
33+
public boolean hasNext() {
34+
return current != null;
35+
}
36+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
284\. Peeking Iterator
2+
3+
Medium
4+
5+
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
6+
7+
Implement the `PeekingIterator` class:
8+
9+
* `PeekingIterator(Iterator<int> nums)` Initializes the object with the given integer iterator `iterator`.
10+
* `int next()` Returns the next element in the array and moves the pointer to the next element.
11+
* `boolean hasNext()` Returns `true` if there are still elements in the array.
12+
* `int peek()` Returns the next element in the array **without** moving the pointer.
13+
14+
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
15+
16+
**Example 1:**
17+
18+
**Input**
19+
20+
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
21+
[[[1, 2, 3]], [], [], [], [], []]
22+
23+
**Output:** \[null, 1, 2, 2, 3, false\]
24+
25+
**Explanation:**
26+
27+
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
28+
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
29+
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
30+
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
31+
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
32+
peekingIterator.hasNext(); // return False
33+
34+
**Constraints:**
35+
36+
* `1 <= nums.length <= 1000`
37+
* `1 <= nums[i] <= 1000`
38+
* All the calls to `next` and `peek` are valid.
39+
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
40+
41+
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package g0201_0300.s0287_find_the_duplicate_number;
2+
3+
public class Solution {
4+
public int findDuplicate(int[] nums) {
5+
int[] arr = new int[nums.length + 1];
6+
for (int i = 0; i < nums.length; ++i) {
7+
arr[nums[i]] += 1;
8+
if (arr[nums[i]] == 2) {
9+
return nums[i];
10+
}
11+
}
12+
return 0;
13+
}
14+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
287\. Find the Duplicate Number
2+
3+
Medium
4+
5+
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
6+
7+
There is only **one repeated number** in `nums`, return _this repeated number_.
8+
9+
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
10+
11+
**Example 1:**
12+
13+
**Input:** nums = \[1,3,4,2,2\]
14+
15+
**Output:** 2
16+
17+
**Example 2:**
18+
19+
**Input:** nums = \[3,1,3,4,2\]
20+
21+
**Output:** 3
22+
23+
**Example 3:**
24+
25+
**Input:** nums = \[1,1\]
26+
27+
**Output:** 1
28+
29+
**Example 4:**
30+
31+
**Input:** nums = \[1,1,2\]
32+
33+
**Output:** 1
34+
35+
**Constraints:**
36+
37+
* <code>1 <= n <= 10<sup>5</sup></code>
38+
* `nums.length == n + 1`
39+
* `1 <= nums[i] <= n`
40+
* All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
41+
42+
**Follow up:**
43+
44+
* How can we prove that at least one duplicate number must exist in `nums`?
45+
* Can you solve the problem in linear runtime complexity?
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package g0201_0300.s0289_game_of_life;
2+
3+
public class Solution {
4+
public void gameOfLife(int[][] board) {
5+
int m = board.length;
6+
int n = board[0].length;
7+
for (int i = 0; i < m; i++) {
8+
for (int j = 0; j < n; j++) {
9+
int lives = lives(board, i, j, m, n);
10+
if (board[i][j] == 0 && lives == 3) {
11+
board[i][j] = 2;
12+
} else if (board[i][j] == 1 && (lives == 2 || lives == 3)) {
13+
board[i][j] = 3;
14+
}
15+
}
16+
}
17+
for (int i = 0; i < m; i++) {
18+
for (int j = 0; j < n; j++) {
19+
board[i][j] >>= 1;
20+
}
21+
}
22+
}
23+
24+
private int lives(int[][] board, int i, int j, int m, int n) {
25+
int lives = 0;
26+
for (int r = Math.max(0, i - 1); r <= Math.min(m - 1, i + 1); r++) {
27+
for (int c = Math.max(0, j - 1); c <= Math.min(n - 1, j + 1); c++) {
28+
lives += board[r][c] & 1;
29+
}
30+
}
31+
lives -= board[i][j] & 1;
32+
return lives;
33+
}
34+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
289\. Game of Life
2+
3+
Medium
4+
5+
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
6+
7+
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
8+
9+
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
10+
2. Any live cell with two or three live neighbors lives on to the next generation.
11+
3. Any live cell with more than three live neighbors dies, as if by over-population.
12+
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
13+
14+
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
15+
16+
**Example 1:**
17+
18+
![](https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg)
19+
20+
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
21+
22+
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
23+
24+
**Example 2:**
25+
26+
![](https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg)
27+
28+
**Input:** board = \[\[1,1\],\[1,0\]\]
29+
30+
**Output:** \[\[1,1\],\[1,1\]\]
31+
32+
**Constraints:**
33+
34+
* `m == board.length`
35+
* `n == board[i].length`
36+
* `1 <= m, n <= 25`
37+
* `board[i][j]` is `0` or `1`.
38+
39+
**Follow up:**
40+
41+
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
42+
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package g0201_0300.s0290_word_pattern;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class Solution {
7+
public boolean wordPattern(String pattern, String s) {
8+
Map<Character, String> map = new HashMap<>();
9+
String[] words = s.split(" ");
10+
if (words.length != pattern.length()) {
11+
return false;
12+
}
13+
for (int i = 0; i < pattern.length(); i++) {
14+
if (!map.containsKey(pattern.charAt(i))) {
15+
if (map.containsValue(words[i])) {
16+
return false;
17+
}
18+
map.put(pattern.charAt(i), words[i]);
19+
} else {
20+
if (!words[i].equals(map.get(pattern.charAt(i)))) {
21+
return false;
22+
}
23+
}
24+
}
25+
return true;
26+
}
27+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
290\. Word Pattern
2+
3+
Easy
4+
5+
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
6+
7+
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
8+
9+
**Example 1:**
10+
11+
**Input:** pattern = "abba", s = "dog cat cat dog"
12+
13+
**Output:** true
14+
15+
**Example 2:**
16+
17+
**Input:** pattern = "abba", s = "dog cat cat fish"
18+
19+
**Output:** false
20+
21+
**Example 3:**
22+
23+
**Input:** pattern = "aaaa", s = "dog cat cat dog"
24+
25+
**Output:** false
26+
27+
**Example 4:**
28+
29+
**Input:** pattern = "abba", s = "dog dog dog dog"
30+
31+
**Output:** false
32+
33+
**Constraints:**
34+
35+
* `1 <= pattern.length <= 300`
36+
* `pattern` contains only lower-case English letters.
37+
* `1 <= s.length <= 3000`
38+
* `s` contains only lower-case English letters and spaces `' '`.
39+
* `s` **does not contain** any leading or trailing spaces.
40+
* All the words in `s` are separated by a **single space**.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package g0201_0300.s0284_peeking_iterator;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import java.util.Arrays;
7+
import org.junit.Test;
8+
9+
public class PeekingIteratorTest {
10+
@Test
11+
public void peekingIterator() {
12+
// [1,2,3]
13+
PeekingIterator peekingIterator = new PeekingIterator(Arrays.asList(1, 2, 3).iterator());
14+
// return 1, the pointer moves to the next element [1,2,3].
15+
assertThat(peekingIterator.next(), equalTo(1));
16+
// return 2, the pointer does not move [1,2,3].
17+
assertThat(peekingIterator.peek(), equalTo(2));
18+
// return 2, the pointer moves to the next element [1,2,3]
19+
assertThat(peekingIterator.next(), equalTo(2));
20+
// return 3, the pointer moves to the next element [1,2,3]
21+
assertThat(peekingIterator.next(), equalTo(3));
22+
// return False
23+
assertThat(peekingIterator.hasNext(), equalTo(false));
24+
}
25+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g0201_0300.s0287_find_the_duplicate_number;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.Test;
7+
8+
public class SolutionTest {
9+
@Test
10+
public void findDuplicate() {
11+
assertThat(new Solution().findDuplicate(new int[] {1, 3, 4, 2, 2}), equalTo(2));
12+
}
13+
14+
@Test
15+
public void findDuplicate2() {
16+
assertThat(new Solution().findDuplicate(new int[] {3, 1, 3, 4, 2}), equalTo(3));
17+
}
18+
19+
@Test
20+
public void findDuplicate3() {
21+
assertThat(new Solution().findDuplicate(new int[] {1, 1}), equalTo(1));
22+
}
23+
24+
@Test
25+
public void findDuplicate4() {
26+
assertThat(new Solution().findDuplicate(new int[] {1, 1, 2}), equalTo(1));
27+
}
28+
}

0 commit comments

Comments
 (0)