Skip to content

Commit 1043872

Browse files
committed
Add MissingNumber task solution
1 parent 3b37624 commit 1043872

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package by.andd3dfx.numeric;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/missing-number/description/">Task description</a>
6+
*
7+
* Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
8+
*
9+
* Example 1:
10+
* Input: nums = [3,0,1]
11+
* Output: 2
12+
* Explanation:
13+
* n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
14+
*
15+
* Example 2:
16+
* Input: nums = [0,1]
17+
* Output: 2
18+
* Explanation:
19+
* n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
20+
*
21+
* Example 3:
22+
* Input: nums = [9,6,4,2,3,5,7,0,1]
23+
* Output: 8
24+
* Explanation:
25+
* n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
26+
* </pre>
27+
*/
28+
public class MissingNumber {
29+
30+
public int missingNumber(int[] nums) {
31+
var n = nums.length;
32+
var flags = new boolean[n + 1];
33+
for (var num : nums) {
34+
flags[num] = true;
35+
}
36+
for (var i = 0; i <= n; i++) {
37+
if (!flags[i]) {
38+
return i;
39+
}
40+
}
41+
return -1;
42+
}
43+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package by.andd3dfx.numeric;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class MissingNumberTest {
8+
9+
private final MissingNumber missingNumber = new MissingNumber();
10+
11+
@Test
12+
public void testMissingNumber() {
13+
assertThat(missingNumber.missingNumber(new int[]{3, 0, 1})).isEqualTo(2);
14+
assertThat(missingNumber.missingNumber(new int[]{0, 1})).isEqualTo(2);
15+
assertThat(missingNumber.missingNumber(new int[]{9, 6, 4, 2, 3, 5, 7, 0, 1})).isEqualTo(8);
16+
}
17+
}

0 commit comments

Comments
 (0)