Leetcode题解 217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

用hashmap解决

public static boolean containsDuplicate(int[] nums) {
        int count = 0;
        if (nums.length == 0) {
            return false;
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) != null) {
                count = map.get(nums[i]);
                count++;
            } else {
                count = 1;
            }
            map.put(nums[i], count);
        }
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            int key = (int) it.next();
            if (map.get(key) > 1) {
                return true;
            }
        }
        return false;
    }

你可能感兴趣的:(LeetCode)