力扣-数据结构-存在重复元素

解法一:从小到大排序后,判断相邻的元素是否重复

 

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }
}

 

 

解法二:放入哈希表中判断是否存在

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for (int x : nums) {
            if (!set.add(x)) {
                return true;
            }
        }
        return false;
    }
}

 

解法三:stream

public boolean containsDuplicate(int[] nums) {
     return Arrays.stream(nums).distinct().count() < nums.length;
}

 

posted @ 2021-10-23 23:59  遮面阿毛  阅读(33)  评论(0)    收藏  举报