diff --git a/lcci/17.04.Missing Number/README.md b/lcci/17.04.Missing Number/README.md index 77ec170e6d1aa..88ab47978b1a5 100644 --- a/lcci/17.04.Missing Number/README.md +++ b/lcci/17.04.Missing Number/README.md @@ -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 + } +} +``` + ### 方法二:求和 @@ -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, +) + } +} +``` + ### 方法三:位运算 diff --git a/lcci/17.04.Missing Number/README_EN.md b/lcci/17.04.Missing Number/README_EN.md index 8d0c402b9388e..f0e867e6a31d8 100644 --- a/lcci/17.04.Missing Number/README_EN.md +++ b/lcci/17.04.Missing Number/README_EN.md @@ -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 + } +} +``` + ### Solution 2 @@ -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, +) + } +} +``` + ### Solution 3 diff --git a/lcci/17.04.Missing Number/Solution.swift b/lcci/17.04.Missing Number/Solution.swift new file mode 100644 index 0000000000000..46cae2cc9e1f6 --- /dev/null +++ b/lcci/17.04.Missing Number/Solution.swift @@ -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 + } +} diff --git a/lcci/17.04.Missing Number/Solution2.swift b/lcci/17.04.Missing Number/Solution2.swift new file mode 100644 index 0000000000000..ec64d3a4b404a --- /dev/null +++ b/lcci/17.04.Missing Number/Solution2.swift @@ -0,0 +1,6 @@ +class Solution { + func missingNumber(_ nums: [Int]) -> Int { + let n = nums.count + return n * (n + 1) / 2 - nums.reduce(0, +) + } +}