1. 程式人生 > >[Swift]LeetCode268. 缺失數字 | Missing Number

[Swift]LeetCode268. 缺失數字 | Missing Number

ret while numbers turn span 包含 ini col example

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

給定一個包含 0, 1, 2, ..., nn 個數的序列,找出 0 .. n 中沒有出現在序列中的那個數。

示例 1:

輸入: [3,0,1]
輸出: 2

示例 2:

輸入: [9,6,4,2,3,5,7,0,1]
輸出: 8

說明:
你的算法應具有線性時間復雜度。你能否僅使用額外常數空間來實現?


 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         //利用異或運算,將數組全體內容與0~n進行異或,
 4         //根據異或運算的性質可知最後結果為缺少的那個數字。
5 var result:Int = nums.count 6 for i in 0..<nums.count 7 { 8 result ^= i ^ nums[i] 9 } 10 return result 11 } 12 }

28ms

1 class Solution {
2     func missingNumber(_ nums: [Int]) -> Int {
3         var h = (nums.count+1
)*nums.count/2 4 for i in 0..<nums.count { 5 h -= nums[i] 6 } 7 return h 8 } 9 }

24ms

 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         var sum = 0 
 4         var max = 0
 5         var i = 0
 6         while i < nums.count {
 7             max = max + i
 8             sum = sum + nums[i]
 9             i = i + 1
10         }
11         return max - sum + i
12     }
13 }

32ms:

求出從0~n的累加和,減去數組整體的和,那麽由於數組內每個數字不相同,其差就是缺少的那個數字

 1 class Solution {
 2     func missingNumber(_ nums: [Int]) -> Int {
 3         let count = nums.count
 4         var sum = count + (count * (count - 1)) / 2
 5         
 6         for i in 0..<count {
 7             sum -= nums[i]
 8         }
 9         return sum
10     }
11 }

[Swift]LeetCode268. 缺失數字 | Missing Number