Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add swift implementation to lcci problem: No.17.04 #2772

Merged
merged 5 commits into from
May 9, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update README.md
  • Loading branch information
yanglbme authored May 9, 2024
commit f5bca310fd23714f44259dc11c1f8a4bf7a74f8d
20 changes: 16 additions & 4 deletions lcci/17.04.Missing Number/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,13 @@ var missingNumber = function (nums) {
```swift
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let n = nums.count
let expectedSum = n * (n + 1) / 2
let actualSum = nums.reduce(0, +)
return expectedSum - actualSum
let nums = nums.sorted()
for (i, x) in nums.enumerated() {
if i != x {
return i
}
}
return nums.count
}
}
```
Expand Down Expand Up @@ -217,6 +220,15 @@ var missingNumber = function (nums) {
};
```

```swift
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let n = nums.count
return n * (n + 1) / 2 - nums.reduce(0, +)
}
}
```

<!-- tabs:end -->

### 方法三:位运算
Expand Down
Loading