找出数组中重复的数字---多思路

问题:找出数组中重复的数字。


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

示例 1:

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

限制:

2 <= n <= 100000

解题思路:

  • 1.利用HashSet,因为HashSet不允许集合中出现重复的元素,通过将数组元素添加到HashSet中,如果元素添加失败,返回false,则元素重复,返回该元素。
  • 2.因为元素值小于数组长度,这里利用元素下标,通过swap函数交换元素位置,将数组中的元素值与其下标值一一对应,即元素值=下标值,若在交换的过程中存在,要交换的元素值==交换位置的元素值,则交换失败,该元素在数组中重复。

代码实现

class Solution{
    //方法1
    public int findRepeatNumber(int [] nums){
        //hash表
        Set<Integer> set=new HashSet<>();
        int res=-1;
        for (int num:nums){
            //add失败,返回false 则找到了某个重复的元素
            if (!set.add(num)){
                res=num;
                break;
            }
        }
        return res;
    }
    
    //方法2
    public int findRepeatNumber2(int [] nums) {
        int n = nums.length;
        for (int num : nums) {
            if (num < 0 || num > n) {
                return -1;
            }
        }
        //利用下标交换元素,即下标值=元素值
        for (int i = 0; i < n; i++) {
            while (nums[i] != i && nums[nums[i]] != nums[i]) {
                //交换nums[i]和nums[nums[i]],如交换nums[0]=2和nums[2]=1
                swap(nums,i,nums[i]);
            }
            if (nums[i] != i && nums[nums[i]] == nums[i]) {
                return nums[i];
            }
        }
        return -1;
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33626996/article/details/111223746