File tree 1 file changed +16
-4
lines changed
lcci/17.04.Missing Number
1 file changed +16
-4
lines changed Original file line number Diff line number Diff line change @@ -122,10 +122,13 @@ var missingNumber = function (nums) {
122
122
``` swift
123
123
class Solution {
124
124
func missingNumber (_ nums : [Int ]) -> Int {
125
- let n = nums.count
126
- let expectedSum = n * (n + 1 ) / 2
127
- let actualSum = nums.reduce (0 , + )
128
- return expectedSum - actualSum
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
129
132
}
130
133
}
131
134
```
@@ -217,6 +220,15 @@ var missingNumber = function (nums) {
217
220
};
218
221
```
219
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
+
220
232
<!-- tabs: end -->
221
233
222
234
### 方法三:位运算
You can’t perform that action at this time.
0 commit comments