[Swift]LeetCode136. 只出現一次的數字 | Single Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fasvoegc-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a non-empty array of integers, every element appears twice except for one. Find that single one.git

Note:github

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?算法

Example 1:數組

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

Example 2:微信

Input: [4,1,2,1,2]
Output: 4

給定一個非空整數數組,除了某個元素只出現一次之外,其他每一個元素均出現兩次。找出那個只出現了一次的元素。app

說明:spa

你的算法應該具備線性時間複雜度。 你能夠不使用額外空間來實現嗎?code

示例 1:htm

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

示例 2:

輸入: [4,1,2,1,2]
輸出: 4

16ms
 1 class Solution {
 2     func singleNumber(_ nums: [Int]) -> Int {
 3         var result = nums.first!
 4         
 5         for index in 1..<nums.count {
 6             result = result ^ nums[index]
 7         }
 8         
 9         return result;
10     }
11 }

48ms
 1 class Solution {
 2     func singleNumber(_ nums: [Int]) -> Int {
 3         // 2 * (a + b) - (a + b + a) = b
 4         let set = Set(nums)
 5         let setSum = set.reduce(0, +)
 6         let arrSum = nums.reduce(0, +)
 7     
 8         return 2 * setSum - arrSum
 9     }
10 }

84ms

 1 class Solution {
 2     func singleNumber(_ nums: [Int]) -> Int {
 3         var set = Set<Int>()
 4     
 5         for item in nums
 6         {
 7             if set.contains(item) {
 8                 set.remove(item)
 9             }
10             else
11             {
12                 set.insert(item)
13             }
14         }
15 
16         return set.popFirst()!
17     }
18 }

96ms

1 class Solution {
2     func singleNumber(_ nums: [Int]) -> Int {
3         return nums.reduce(0, { $0^$1 })
4     }
5 }

108ms

 1 class Solution {
 2     func singleNumber(_ nums: [Int]) -> Int {
 3         var dict: [Int: Int] = [:]
 4         
 5         for num in nums {
 6             dict[num] = (dict[num] ?? 0) + 1
 7         }
 8         
 9         for num in dict.keys {
10             if dict[num] == 1 {
11                 return num
12             }
13         }
14         
15         return 0
16     }
17 }

112ms

1 class Solution {
2     func singleNumber(_ nums: [Int]) -> Int {
3 
4    return nums.reduce(0, ^)
5   }
6 }
相關文章
相關標籤/搜索