260. Single Number III
- Total Accepted: 42681
- Total Submissions: 92409
- Difficulty: Medium
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.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
public class Solution { //改完下面的语法错误,一次通过。。哎,语法错误。。。
public int[] singleNumber(int[] nums) {
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
int length = nums.length;//注意获得数组的长度,不是length(),而是直接 .length
if(length<=1)return nums;
for(int i=0;i<length;i++){
if(hm.containsKey(nums[i])==false) //注意没有getKey方法,只有containsKey方法,返回值为Boolean型
hm.put(nums[i],1);
else{
int temp = hm.get(nums[i])+1;//注意用get方法获取值
hm.put(nums[i],temp);
}
}
LinkedList<Integer> list = new LinkedList<Integer>();
for(int i:hm.keySet()){
if(hm.get(i)==1)//注意没有getValue方法,只有get方法获取值
list.add(i);
}
int[] ret= new int[list.size()];//注意数组的初始化
//Collections.addAll(ret,list);//类型不对应
//return list.toIntegerArray();//注意没toIntegerArray()方法
for(int i=0;i<list.size();i++){ //注意list长度是.size()方法
ret[i]=list.get(i);
}
return ret;
}
}