HashMap-面試題56 - II. 數組中數字出現的次數 II

c++:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        unordered_map<int,int>mp;
        for(auto n:nums) mp[n]++;
        for(auto n:nums){
            if(mp[n]==1) return n;
        }
        return 0;
    }
};

 Java:HashMap

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> map=new HashMap<>();
        for(int i:nums){
            if(map.get(i)==null) map.put(i,1);
            else map.put(i,map.get(i)+1);
        }
        for(int i:nums){
            if(map.get(i)==1) return i;
        }
        return -1;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章