8000 add 268 solution · zykjcom/leetcode@5b700e3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5b700e3

Browse files
committed
add 268 solution
1 parent 036d9b9 commit 5b700e3

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# 268. Missing Number
2+
3+
## #1 等差数组求和公式[AC]
4+
5+
### 思路
6+
7+
我们利用一个特性,就是$sum = 0+1+2+…+n = \frac{n(n+1)}{2}$,如果里面有一个值(不妨设为m)丢失,那最后得到的求和结果就是$sum\_miss = \frac{n(n+1)}{2}-m$。所以,我们简单的就是公式变换,就可以得到$m$的值了。
8+
9+
### 算法
10+
11+
```java
12+
class Solution {
13+
public int missingNumber(int[] nums) {
14+
if(nums == null || nums.length == 0)
15+
return -1;
16+
int n = nums.length;
17+
int sum = n*(n+1)/2;
18+
for(int num : nums)
19+
sum -= num;
20+
return sum;
21+
}
22+
}
23+
```
24+
25+
### 复杂度分析
26+
27+
- **时间复杂度**:$O(n)$
28+
- **空间复杂度**:$O(1)$
29+
30+
## #2 排序[AC]
31+
32+
### 思路
33+
34+
先对数组进行排序,如果数组中没有数据丢失,那么对于每个元素,必然满足`nums[i] = nums[i-1]+1`(除了第一个元素外),因为有元素丢失,所以这个性质被破坏,我们只需要找出在哪个元素破坏了上面这个性质即可。
35+
36+
### 算法
37+
38+
```java
39+
class Solution {
40+
public int missingNumber(int[] nums) {
41+
if(nums == null || nums.length == 0)
42+
return -1;
43+
Arrays.sort(nums);
44+
if(nums[0] != 0)
45+
return 0;
46+
for(int i=1; i<nums.length; i++){
47+
if(nums[i] != nums[i-1]+1)
48+
return nums[i-1]+1;
49+
}
50+
return nums.length;
51+
}
52+
}
53+
```
54+
55+
### 复杂度分析
56+
57+
- 时间复杂度**:$O(nlogn)$
58+
- **空间复杂度**:$O(1)$
59+
60+
## #3 位操作[AC]
61+
62+
### 思路
63+
64+
位操作是利用XOR(异或)这个运算特性来做的,在[Single Number](https://leetcode.com/problems/single-number)[Single Number III](https://leetcode.com/problems/single-number-iii)的题目中,我们利用XOR操作来找到数组中只出现一次的元素(其他元素都出现两次),那么对于这道题目我们是否也可以这样做的。乍一看,数组似乎就没有重复的元素嘛,但是我们如果把数组的`index`和数组的最大值加上,就会出现缺失值只出现一次,其他元素出现两次这样的数组了,非常的巧妙。
65+
66+
**Miss = 4**
67+
68+
| Index | 0 | 1 | 2 | 3 |
69+
| ----- | ---- | ---- | ---- | ---- |
70+
| Value | 0 | 1 | 3 | 4 |
71+
72+
我们得到的数组为:`[0,0,1,1,2,3,3,4]`,然后只出现一次的2就是我们要找的答案了。
73+
74+
### 算法
75+
76+
```java
77+
class Solution {
78+
public int missingNumber(int[] nums) {
79+
if(nums == null || nums.length == 0)
80+
return -1;
81+
int miss = nums.length;
82+
for(int i=0; i<nums.length; i++){
83+
miss ^= i;
84+
miss ^= nums[i];
85+
}
86+
return miss;
87+
}
88+
}
89+
```
90+
91+
### 复杂度分析
92+
93+
- **时间复杂度**:$O(n)$
94+
- **空间复杂度**:$O(1)$
95+

0 commit comments

Comments
 (0)
0