码迷,mamicode.com
首页 > 编程语言 > 详细

【剑指Offer】03. 数组中重复的数字

时间:2020-04-09 00:27:30      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:元素   http   范围   哈希   映射   code   交换   ref   重复数   

题目链接
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 
限制:
2 <= n <= 100000

解法一:最简单的,排序后找重复的

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

解法二:哈希

class Solution {
    public int findRepeatNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int num : nums){
            if(!set.add(num)){
                return num;
            }
        }
        return 0;
    }
}

解法三:原地哈希
将每个位置的数交换映射到其对应的数组下标,当出现新的元素与其对应的下标中的数字相等时,即为重复数字

class Solution {
    public int findRepeatNumber(int[] nums) {
        int len = nums.length;
        for(int i = 0; i < len; i++){
            while(nums[i] != i){
                if(nums[i] == nums[nums[i]]){
                    return nums[i];
                }
                int temp = nums[i];
                nums[i] = nums[temp];
                nums[temp] = temp;
            }
        }
        return 0;
    }
}

【剑指Offer】03. 数组中重复的数字

标签:元素   http   范围   哈希   映射   code   交换   ref   重复数   

原文地址:https://www.cnblogs.com/whisperbb/p/12663808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!