资讯专栏INFORMATION COLUMN

[LeetCode] Contains Duplicate

褰辩话 / 1418人阅读

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.

Solution Use HashSet
class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums == null || nums.length == 0) return false;
        HashSet set = new HashSet<>();
        for (int num: nums) {
            if (set.contains(num)) {
                return true;
            } else {
                set.add(num);
            }
        }
        return false;
    }
}
Sort and compare adjacent numbers
class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums == null || nums.length < 2) return false;
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i-1]) return true;
        }
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76380.html

相关文章

  • [Leetcode] Contains Duplicate 包含重复

    摘要:代码集合法复杂度时间空间思路同样使用集合,但这次我们要维护集合的大小不超过,相当于是记录一个宽度为的窗口中出现过的数字。 Contains Duplicate I Given an array of integers, find if the array contains any duplicates. Your function should return true if any v...

    rozbo 评论0 收藏0
  • Leetcode PHP题解--D90 217. Contains Duplicate

    摘要:题目链接题目分析返回给定的数组中是否有元素重复出现。思路用和即可最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D90 217. Contains Duplicate 题目链接 217. Contains Duplicate 题目分析 返回给定的数组中是否有元素重复出现。 思路 用count和array_unique即可 最终代码

    mingde 评论0 收藏0
  • leetcode217.219.220 contains duplicate

    摘要:输入一个整数数组,查看数组中是否存在重复的值。新的数组中数组的下标为原数组的值,如果遍历过,则设置为。这里使用了作为实现的数据结构,通过堆的形式对集合中的数据进行存储,从而我们可以通过某种顺序获得该集合中的所有顺序。 217 Contains Duplicate Given an array of integers, find if the array contains any dup...

    tulayang 评论0 收藏0
  • [LintCode/LeetCode] Contains Duplicate II

    Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at ...

    894974231 评论0 收藏0
  • leetcode 217 Contains Duplicate

    摘要:题目详情输入一个整数的数组,如果数组中的元素有重复的,那么返回,如果数组中的元素都是唯一的,那么返回思路这道题理解起来比较简单,首先还是要注意一下边界条件异常输入,对于长度小于等于的数组做一个直接的返回对于这种要考虑数组中元素的重复的问题, 题目详情 Given an array of integers, find if the array contains any duplicate...

    philadelphia 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<