问题描述
解法 1
分析
Python 实现
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class : def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ans = set() for num in nums: if num in ans: ans.remove(num) else: ans.add(num) return ans.pop()
|
Java 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class { public int singleNumber(int[] nums) { Set<Integer> ans = new HashSet<>(); for(int num : nums){ if(ans.contains(num)){ ans.remove(num); }else{ ans.add(num); } } return ans.iterator().next(); } }
|
时间复杂度
O(n).
空间复杂度
O(n).
解法 2
Python 实现
1 2 3 4 5 6 7
|
class : def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ return 2*sum(set(nums)) - sum(nums)
|
Java 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class { public int singleNumber(int[] nums) { int sum = 0; int set_sum = 0; Set<Integer> set = new HashSet<>(); for(int num : nums){ set.add(num); sum += num; } for(int num : set){ set_sum += num; } return 2 * set_sum - sum; } }
|
时间复杂度
O(n).
空间复杂度
O(n).
链接
136. Single Number
136. 只出现一次的数字
(English version) Algorithm Notes: Leetcode#136 Single Number
近期评论