LeetCode第136题

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4

思路:1.将整形数组中的元素存到hashmap中,键为数组中的值,值为出现的次数

           2.对hashmap进行遍历,将键值对的值中等于1的数给取出来

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

猜你喜欢

转载自blog.csdn.net/qq_37764098/article/details/84560050