Leetcode刷题java之287. 寻找重复数

执行结果:

通过

显示详情

执行用时 :5 ms, 在所有 Java 提交中击败了33.14% 的用户

内存消耗 :38.1 MB, 在所有 Java 提交中击败了19.45%的用户

题目:

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:

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


示例 2:

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

扫描二维码关注公众号,回复: 9349608 查看本文章


说明:


    不能更改原数组(假设数组是只读的)。
    只能使用额外的 O(1) 的空间。
    时间复杂度小于 O(n2) 。
    数组中只有一个重复的数字,但它可能不止重复出现一次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-duplicate-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

用一个hashset来解决

代码:

class Solution {
    public int findDuplicate(int[] nums) {
        Set<Integer> hash=new HashSet<>();
        for(int num:nums)
        {
            if(hash.contains(num))
            {
                return num;
            }else
            {
                hash.add(num);
            }
        }
        return -1;
    }
}
发布了481 篇原创文章 · 获赞 502 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/104233129