【java】217. 存在重复元素---不确定数组大小,用集合!!!

给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

示例 1:

输入: [1,2,3,1]
输出: true
示例 2:

输入: [1,2,3,4]
输出: false
示例 3:

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

public static  boolean containsDuplicate(int[] nums) {
    
    
		Map<Integer,Integer> map=new HashMap<Integer, Integer>();
		for(int i=0;i<nums.length;i++) {
    
    
			map.put(nums[i], map.getOrDefault(nums[i],0)+1);
			if(map.get(nums[i])>1) {
    
    
				return true;
			}
		}
		return false;
    }

猜你喜欢

转载自blog.csdn.net/qq_44461217/article/details/111088803