LeetCode137.只出现一次的数字
给你一个整数数组 nums
,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
。请你找出并返回那个只出现了一次的元素。你必须设计并实现线性时间复杂度的算法且不使用额外空间来解决此问题。示例:
输入:nums = [2,2,3,2]
输出:3
输入:nums = [0,1,0,1,0,1,99]
输出:99
Method1. HashMap
Python:
collections的Counter来计数可哈希对象,通过一次循环找到次数为1的数字,时间复杂度为O(n),注意要去掉括号。
class Solution:
def singleNumber(self, nums: List[int]) -> int:
freq = collections.Counter(nums)
ans = [num for num, occ in freq.items() if occ == 1][0]
return ans
Java:
使用一次for循环将数组的元素放入hashmap中,利用getOrDefault实现计数,然后利用Map.Entry遍历Map 找到value为1的key,break后return结果。
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i:nums)
{
map.put(i,map.getOrDefault(i,0)+1);
}
int ans=0;
for(Map.Entry<Integer,Integer> entry:map.entrySet())
{
if(entry.getValue()==1){
ans = entry.getKey();
break;
}
}
return ans;
}
}
Method2. HashSet+数学方法(但额外引入了O(k)的空间)
用了HashSet
,设不重复的元素个数为k
,额外引入了O(k)
的空间。
思路很简单:
- 创建一个
HashSet
,一个ans
存放累加结果 - 设原数组所有元素之和为
total
,total = 3*a + x
,a
为重复的元素单独求和一次,x
为只出现一次的元素 - 遍历数组
nums
,如果set.add[nums[i]]
成功,就累加到ans
;如果添加失败,说明set
中已经存在,说明该元素不是目标的只重复一次的元素,就set.remove(nums[i])
出去,这样重复三次的元素在第三次遍历到的时候,会被再次成功加入set
中,故再次累加到ans
,最终ans = 2*a + x
- 显而易见,结果为
x = 3*a + x-3*[(3*a + x)-(2*a + x)]
,即total-3*(total-ans)
class Solution {
public int singleNumber(int[] nums) {
int total = Sum(nums);
Set set = new HashSet();
int ans = 0;
for (int i = 0, len = nums.length; i < len; i++) {
if (set.add(nums[i])) ans += nums[i];
else set.remove(nums[i]);
}
return total-3*(total-ans);
}
public int Sum(int[] Array)
{
int ans = 0;
for(int i = 0; i < Array.length; i++)
{
ans += Array[i];
}
return ans;
}
}