【剑指offer】3-1数组中重复的数字

题目描述

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

例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路

1.暴力法

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

2.哈希表

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

对重复问题经常用到哈希表,但是哈希表的空间复杂度是O(n)

3.置换

class Solution {
    public int findRepeatNumber(int[] nums) {
        for(int i = 0; i < nums.length; i++){
            while(i != nums[i]){
                if(nums[i] < 0 || nums[i] >= nums.length) return -1;
                if(nums[i] == nums[nums[i]]){
                    return nums[i];
                }
                int temp = nums[i];
                nums[i] = nums[temp];
                nums[temp] = temp;
            }
        }  
        return -1;
    }
}
发布了89 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Dawn510/article/details/105086495