[Lintcode]82. Single Number/[Leetcode]136. Single Number
阿新 • • 發佈:2019-02-10
一個 algorithm lintcode www. 思路 n) num item hat
82. Single Number/136. Single Number
- 本題難度: Easy
- Topic: Greedy
Description
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
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
我的代碼
class Solution:
"""
@param A: An integer array
@return: An integer
"""
def singleNumber(self, A):
# write your code here
res = 0
for i in A:
res = res^i
return res
別人的代碼 參考
#開辟一個字典 def singleNumber1(self, nums): dic = {} for num in nums: dic[num] = dic.get(num, 0)+1 for key, val in dic.items(): if val == 1: return key #異或 def singleNumber2(self, nums): res = 0 for num in nums: res ^= num return res #利用了set def singleNumber3(self, nums): return 2*sum(set(nums))-sum(nums) #reduce #異或 def singleNumber4(self, nums): return reduce(lambda x, y: x ^ y, nums) #reduce #異或 def singleNumber(self, nums): return reduce(operator.xor, nums)
思路
相同的數字,異或為0
- 時間復雜度 O(log(n))
[Lintcode]82. Single Number/[Leetcode]136. Single Number