2017.9.29
这个题目是要求输出第一个非唯一的元素。如果直接用HashMap的话会失去顺序,所以需要使用LinkedHashMap。
public class Solution {
/*
* @param : a continuous stream of numbers
* @param : a number
* @return: returns the first unique number
*/
public int firstUniqueNumber(int[] nums, int number) {
// Write your code here
if(nums == null){
return -1;
}
int res = -1;
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
boolean find = false;
for(int i = 0; i < nums.length; i++){
if(nums[i] == number){
find = true;
break;
}
if(!map.containsKey(nums[i])){
map.put(nums[i], 1);
}
else{
map.put(nums[i], map.get(nums[i]) + 1);
}
}
if(find == false){
return res;
}
Iterator ite = map.keySet().iterator();
while(ite.hasNext()){
int tmp = (int)ite.next();
if(map.get(tmp) == 1){
res = tmp;
break;
}
}
return res;
}
};