Given an array of integers, every element appears twice except for one. Find that single one.
題目很直接,直接建哈希表,遍歷,在表中就刪除元素,不在表中就加入表,最後表中只剩下一個元素,返回其值:
public class Solution {
public int singleNumber(int[] A) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int i,len=A.length;
for(i=0;i<len;i++)
{
if(map.containsKey(A[i]))map.remove(A[i]);
else
{
map.put(A[i],1);
}
}
return map.keySet().iterator().next();
}
}
上面是常規做法,在其他地方看到一個非常好的做法,其實兩個相同的數的異或所有爲都置一,將數組中所有的數依次取異或,最後得到的值即爲單獨出現依次的數:
public class Solution {
public int singleNumber(int[] A) {
int x=0;
for(int a:A)x=x^a;
return x;
}
}
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
與之前解法相似,遍歷時加入判定當有2個元素在表中時再刪除元素,最後返回表中剩下的元素
public class Solution {
public int singleNumber(int[] A) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int len=A.length;
for(int i=0;i<len;i++)
{
if(map.containsKey(A[i]))
{
int count=map.get(A[i]);
if(count==2)map.remove(A[i]);
else map.put(A[i],++count);
}
else map.put(A[i],1);
}
return map.keySet().iterator().next();
}
}