[Java] 217. There are duplicate elements---unsure of the size of the array, use a collection! ! !

Given an integer array, determine whether there are duplicate elements.

If any value appears at least twice in the array, the function returns true. If every element in the array is different, false is returned.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: 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;
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/111088803