File tree 4 files changed +63
-0
lines changed
lcci/17.04.Missing Number
4 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -119,6 +119,20 @@ var missingNumber = function (nums) {
119
119
};
120
120
```
121
121
122
+ ``` swift
123
+ class Solution {
124
+ func missingNumber (_ nums : [Int ]) -> Int {
125
+ let nums = nums.sorted ()
126
+ for (i, x) in nums.enumerated () {
127
+ if i != x {
128
+ return i
129
+ }
130
+ }
131
+ return nums.count
132
+ }
133
+ }
134
+ ```
135
+
122
136
<!-- tabs: end -->
123
137
124
138
### 方法二:求和
@@ -206,6 +220,15 @@ var missingNumber = function (nums) {
206
220
};
207
221
```
208
222
223
+ ``` swift
224
+ class Solution {
225
+ func missingNumber (_ nums : [Int ]) -> Int {
226
+ let n = nums.count
227
+ return n * (n + 1 ) / 2 - nums.reduce (0 , + )
228
+ }
229
+ }
230
+ ```
231
+
209
232
<!-- tabs: end -->
210
233
211
234
### 方法三:位运算
Original file line number Diff line number Diff line change @@ -119,6 +119,20 @@ var missingNumber = function (nums) {
119
119
};
120
120
```
121
121
122
+ ``` swift
123
+ class Solution {
124
+ func missingNumber (_ nums : [Int ]) -> Int {
125
+ let nums = nums.sorted ()
126
+ for (i, x) in nums.enumerated () {
127
+ if i != x {
128
+ return i
129
+ }
130
+ }
131
+ return nums.count
132
+ }
133
+ }
134
+ ```
135
+
122
136
<!-- tabs: end -->
123
137
124
138
### Solution 2
@@ -202,6 +216,15 @@ var missingNumber = function (nums) {
202
216
};
203
217
```
204
218
219
+ ``` swift
220
+ class Solution {
221
+ func missingNumber (_ nums : [Int ]) -> Int {
222
+ let n = nums.count
223
+ return n * (n + 1 ) / 2 - nums.reduce (0 , + )
224
+ }
225
+ }
226
+ ```
227
+
205
228
<!-- tabs: end -->
206
229
207
230
### Solution 3
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func missingNumber( _ nums: [ Int ] ) -> Int {
3
+ let nums = nums. sorted ( )
4
+ for (i, x) in nums. enumerated ( ) {
5
+ if i != x {
6
+ return i
7
+ }
8
+ }
9
+ return nums. count
10
+ }
11
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func missingNumber( _ nums: [ Int ] ) -> Int {
3
+ let n = nums. count
4
+ return n * ( n + 1 ) / 2 - nums. reduce ( 0 , + )
5
+ }
6
+ }
You can’t perform that action at this time.
0 commit comments