|
1 |
| -# [17.04. Missing Number](https://leetcode-cn.com/problems/missing-number-lcci) |
2 |
| - |
3 |
| -## Description |
4 |
| -<p>An array contains all the integers from 0 to n, except for one number which is missing. Write code to find the missing integer. Can you do it in O(n) time?</p> |
5 |
| -
|
6 |
| -<p><strong>Note: </strong>This problem is slightly different from the original one the book.</p> |
7 |
| -
|
8 |
| -<p><strong>Example 1: </strong></p> |
9 |
| -
|
10 |
| -<pre> |
11 |
| -<strong>Input: </strong>[3,0,1] |
12 |
| -<strong>Output: </strong>2</pre> |
13 |
| -
|
14 |
| -<p> </p> |
15 |
| -
|
16 |
| -<p><strong>Example 2: </strong></p> |
17 |
| -
|
18 |
| -<pre> |
19 |
| -<strong>Input: </strong>[9,6,4,2,3,5,7,0,1] |
20 |
| -<strong>Output: </strong>8 |
21 |
| -</pre> |
22 |
| - |
23 |
| - |
24 |
| - |
25 |
| -## Solutions |
26 |
| - |
27 |
| - |
28 |
| -### Python3 |
29 |
| - |
30 |
| -```python |
31 |
| - |
32 |
| -``` |
33 |
| - |
34 |
| -### Java |
35 |
| - |
36 |
| -```java |
37 |
| - |
38 |
| -``` |
39 |
| - |
40 |
| -### ... |
41 |
| -``` |
42 |
| - |
43 |
| -``` |
| 1 | +# [17.04. Missing Number](https://leetcode-cn.com/problems/missing-number-lcci) |
| 2 | + |
| 3 | +## Description |
| 4 | +<p>An array contains all the integers from 0 to n, except for one number which is missing. Write code to find the missing integer. Can you do it in O(n) time?</p> |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +<p><strong>Note: </strong>This problem is slightly different from the original one the book.</p> |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +<p><strong>Example 1: </strong></p> |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +<pre> |
| 17 | + |
| 18 | +<strong>Input: </strong>[3,0,1] |
| 19 | + |
| 20 | +<strong>Output: </strong>2</pre> |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +<p> </p> |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +<p><strong>Example 2: </strong></p> |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | +<pre> |
| 33 | + |
| 34 | +<strong>Input: </strong>[9,6,4,2,3,5,7,0,1] |
| 35 | + |
| 36 | +<strong>Output: </strong>8 |
| 37 | + |
| 38 | +</pre> |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +## Solutions |
| 44 | + |
| 45 | + |
| 46 | +### Python3 |
| 47 | + |
| 48 | +```python |
| 49 | +class Solution: |
| 50 | + def missingNumber(self, nums: List[int]) -> int: |
| 51 | + res = 0 |
| 52 | + for i, num in enumerate(nums): |
| 53 | + res ^= i |
| 54 | + res ^= num |
| 55 | + res ^= len(nums) |
| 56 | + return res |
| 57 | +``` |
| 58 | + |
| 59 | +### Java |
| 60 | + |
| 61 | +```java |
| 62 | +class Solution { |
| 63 | + public int missingNumber(int[] nums) { |
| 64 | + int res = 0, n = nums.length; |
| 65 | + for (int i = 0; i < n; ++i) { |
| 66 | + res ^= i; |
| 67 | + res ^= nums[i]; |
| 68 | + } |
| 69 | + res ^= n; |
| 70 | + return res; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +### ... |
| 76 | +``` |
| 77 | +
|
| 78 | +``` |
0 commit comments