Skip to content

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

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

Merged
merged 5 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
23 changes: 23 additions & 0 deletions lcci/17.04.Missing Number/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,20 @@ var missingNumber = function (nums) {
};
```

```swift
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let nums = nums.sorted()
for (i, x) in nums.enumerated() {
if i != x {
return i
}
}
return nums.count
}
}
```

<!-- tabs:end -->

### 方法二:求和
Expand Down Expand Up @@ -206,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
23 changes: 23 additions & 0 deletions lcci/17.04.Missing Number/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,20 @@ var missingNumber = function (nums) {
};
```

```swift
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let nums = nums.sorted()
for (i, x) in nums.enumerated() {
if i != x {
return i
}
}
return nums.count
}
}
```

<!-- tabs:end -->

### Solution 2
Expand Down Expand Up @@ -202,6 +216,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 -->

### Solution 3
Expand Down
11 changes: 11 additions & 0 deletions lcci/17.04.Missing Number/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let nums = nums.sorted()
for (i, x) in nums.enumerated() {
if i != x {
return i
}
}
return nums.count
}
}
6 changes: 6 additions & 0 deletions lcci/17.04.Missing Number/Solution2.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let n = nums.count
return n * (n + 1) / 2 - nums.reduce(0, +)
}
}