【題目描述】
給定一個包含 0, 1, 2, ..., n 中 n 個數(shù)的序列缕粹,找出 0 .. n 中沒有出現(xiàn)在序列中的那個數(shù)。
【示例1】
輸入: [3,0,1]
輸出: 2
【示例2】
輸入: [9,6,4,2,3,5,7,0,1]
輸出: 8
【Swift代碼實現(xiàn)】
1纸淮、數(shù)學(xué)方法實現(xiàn)平斩,(0-n的和) 減去 (給出數(shù)組元素之和)= 所求值
func missingNumber(_ nums: [Int]) -> Int {
let sum = nums.count * (nums.count + 1) / 2
var s = 0
for num in nums {
s+=num
}
return sum-s
}
2、異或運算
func missingNumber(_ nums: [Int]) -> Int {
var result = nums.count
for num in 0..<nums.count {
result ^= nums[num]
result ^= num
}
return result
}
異或運算有以下特性:
0^0 = 0咽块,
1^0 = 1绘面,
0^1 = 1,
1^1 = 0;
(1) 0 ^ 0=0侈沪,0^1=1 0異或任何數(shù)=任何數(shù)
(2) 1 ^ 0=1揭璃,1^1=0 1異或任何數(shù)-任何數(shù)取反
(3) 任何數(shù)異或自己=把自己置0