Skip to content

Latest commit

 

History

History
30 lines (21 loc) · 804 Bytes

137. Single Number II.MD

File metadata and controls

30 lines (21 loc) · 804 Bytes

Given an array of integers, every element appears three times except for one. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


这个实现不难,但是不申请空间实现就很难了。

    public int singleNumber(int[] nums) {
       HashMap<Integer,Integer> map = new  HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length ; i++){
        
        	if(!map.containsKey(nums[i])){
        		map.put(nums[i], 1);
        	}else{
        		map.put(nums[i], map.get(nums[i])+1);
        	}
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        	if(entry.getValue() == 1)
        		return entry.getKey();
        }
        
        return 0;
    }