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

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

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof

示列:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

// 1 思路简单:双重循环,时间复杂度:O(n^2),空间占用少,但时间还可以优化【2353ms 46.1MB】

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

// 2 HashMap保存出现的数字【10ms 47.3MB】

class Solution {
    public int findRepeatNumber(int[] nums) {
        int len = nums.length;
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<len;i++){
            if(map.containsKey(nums[i])){
                return nums[i];
            }
            map.put(nums[i],1);
        }
        return -1;
    }
}

// 3 数组长度为n,且数组元素的范围在0 ~ n-1之间,在遍历的过程中,将元素移动到对应的下标(while)【0ms 46MB】

class Solution {
    public int findRepeatNumber(int[] nums) {
        int len = nums.length;
        int temp;
        for(int i=0;i<len;i++){
            while(nums[i] != i){
                if(nums[i] == nums[nums[i]]){
                    return nums[i];
                } // 这块代码我开始是放在了交换语句下面,出错了。当该位置的值归为后就退出了程序【 nums[0] == nums[nums[0]] 】
                temp = nums[nums[i]];
                nums[nums[i]] = nums[i];
                nums[i] = temp;
            }
        }
        return -1;
    }
}
posted @ 2021-05-22 09:31  Manan_vision  阅读(28)  评论(0)    收藏  举报