leetcode每日一题之存在重复元素

leetcode每日一题之存在重复元素

编码文章call10242025-06-15 15:17:184A+A-

题:

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

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

比如:

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

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

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

解:

一、先对数组排序,然后遍历数组,当相邻的元素相等时,则判定有重复元素。其中sort方法时间复杂度为O(nlogn),后面扫描时间复杂度为O(n)可忽略

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

二、创建哈希set集合,其中set集合有去重功能,如果插入一个元素时发现该元素已经存在表中,则说明是重复元素.时间复杂度为O(n)

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;
    }
}

三、Java8新特性stream流一行搞定,去重,然后求元素个数,比较是否和原来数组元素个数相等

class Solution {
    public boolean containsDuplicate(int[] nums) {
     return Arrays.stream(nums).distinct().count() != nums.length;
}

链接:
https://leetcode-cn.com/problems/contains-duplicate

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4