Leetcode 217. Contains Duplicate

作者: ShutLove | 来源:发表于2017-11-27 11:13 被阅读17次

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.

思路:
用哈希表记录已遍历的数字。

public boolean containsDuplicate(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return false;
    }

    HashSet<Integer> set = new HashSet<>();
    for (int num : nums) {
        if (!set.add(num)) {
            return true;
        }
    }

    return false;
}

先对数组排序,然后看有没有相等的相邻数字。

public boolean containsDuplicate(int[] nums) {

    Arrays.sort(nums);
    for(int ind = 1; ind < nums.length; ind++) {
        if(nums[ind] == nums[ind - 1]) {
            return true;
        }
    }
    return false;
}

相关文章

网友评论

    本文标题:Leetcode 217. Contains Duplicate

    本文链接:https://www.haomeiwen.com/subject/mbvrbxtx.html