★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-ppotppvo-ma.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.git
Example:github
Input: Output: [1,2,1,3,2,5][3,5]
Note:算法
[5, 3]
is also correct.給定一個整數數組 nums
,其中剛好有兩個元素只出現一次,其他全部元素均出現兩次。 找出只出現一次的那兩個元素。數組
示例 :微信
輸入: 輸出: [1,2,1,3,2,5][3,5]
注意:app
[5, 3]
也是正確答案。76msspa
1 class Solution { 2 func singleNumber(_ nums: [Int]) -> [Int] { 3 4 var res = [0, 0] 5 var diff = nums.reduce(0){$0 ^ $1} 6 diff &= -diff 7 for num in nums { 8 if num & diff != 0 { 9 res[0] ^= num 10 } 11 else { 12 res[1] ^= num 13 } 14 } 15 return res 16 } 17 }
76mscode
1 class Solution { 2 func singleNumber(_ nums: [Int]) -> [Int] { 3 guard nums.count > 1 else { 4 return nums 5 } 6 7 var result = nums[0] 8 for num in nums[1...] { 9 result ^= num 10 } 11 12 var num1 = 0, num2 = 0, tmp = 1 13 while (result & tmp) == 0 { 14 tmp <<= 1 15 } 16 17 for num in nums { 18 if (num & tmp) > 0 { 19 num1 ^= num 20 } 21 else { 22 num2 ^= num 23 } 24 } 25 26 return [num1, num2] 27 } 28 }
80mshtm
1 class Solution { 2 func singleNumber(_ nums: [Int]) -> [Int] { 3 var s: Set<Int> = Set(minimumCapacity: nums.count) 4 for i in nums { 5 if s.contains(i) { 6 s.remove(i) 7 } else { 8 s.insert(i) 9 } 10 } 11 return Array(s) 12 } 13 }
84ms
1 class Solution { 2 func singleNumber(_ nums: [Int]) -> [Int] { 3 var array = nums.sorted() 4 // print(array) 5 var output:[Int] = [] 6 7 var i = 0 8 while i < array.count { 9 if i == array.count - 1 || array[i] != array[i+1] { 10 output.append(array[i]) 11 } else { 12 i += 1 13 } 14 i += 1 15 if output.count > 1 { 16 break 17 } 18 } 19 20 return output 21 } 22 }
84ms
1 class Solution { 2 func singleNumber(_ nums: [Int]) -> [Int] { 3 var result = [Int]() 4 var temp = nums.sorted() 5 for i in 0..<temp.count { 6 if i == 0 { 7 if temp[i] != temp[i+1] { 8 result.append(temp[i]) 9 } 10 } else if i == temp.count - 1{ 11 if temp[i] != temp[i-1] { 12 result.append(temp[i]) 13 } 14 } 15 else { 16 if temp[i] != temp[i-1] && temp[i] != temp[i+1]{ 17 result.append(temp[i]) 18 } 19 } 20 } 21 return result 22 } 23 }