題目連結: https://leetcode.com/problems/single-number/
XOR方法:
func singleNumber(_ nums: [Int]) -> Int {
return nums.reduce(0) {
$0 ^ $1
}
}
使用Dictionary方法:
func singleNumber(_ nums: [Int]) -> Int {
if nums.count == 0 { return -1 }
else if nums.count == 1 { return nums[0] }
else {
var dic: [Int: Int] = [:]
for item in nums {
dic[item, default: 0] = dic[item, default: 0] + 1
}
for (key, val) in dic {
if val == 1 {
return key
}
}
return -1
}
}
參考:
https://leetcode.com/problems/single-number/discuss/314884/My-4-Swift-Solutions