剑指Offer-01数组中重复的数字

72 阅读1分钟
public static int findRepeatNumber(int[] nums) {

    //由于HashMap的key不重复
    HashMap<Integer,Integer> map = new HashMap<>();
    for (int temp : nums) {
        if (map.containsKey(temp)) {//判断map是否包含这个值 直接返回
            return temp;
        }
        map.put(temp, 0);//不存在 这存入map
    }
    return -1;
}

 

执行时间没有击败100%

看了别人的答案好聪明啊

充分利用题目条件(我没看到啊!细节)

长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内

//优化答案
public static int findRepeatNumber(int[] nums){
    for (int i = 0; i < nums.length; i++) {
        while(i != nums[i]) { //出口 下标与值相等
            if(nums[nums[i]] == nums[i]) { //下标位置已经存在正确的值了 说明重复了
                return nums[i];
            }
            swap(nums, i, nums[i]); //把当前值与相等下标的值互换
        }
    }
    return -1;
}