当前位置:网站首页>Sword finger offer 03 Duplicate number in array

Sword finger offer 03 Duplicate number in array

2022-04-23 17:32:00 hequnwang10

One 、 Title Description

Find the repeated numbers in the array .

At a length of n Array of nums All the numbers in 0~n-1 Within the scope of . Some numbers in the array are repeated , But I don't know how many numbers are repeated , I don't know how many times each number has been repeated . Please find any duplicate number in the array .

Example 1:
 Input :
[2, 3, 1, 0, 2, 5, 3]
 Output :2  or  3 

Two 、 Problem solving

In situ hash

Put the value at the corresponding subscript , Exchange data , If there is duplication, just put back the duplicate data .

class Solution {
    
    public int findRepeatNumber(int[] nums) {
    
        // In situ hash 
        int length = nums.length;
        for(int i = 0;i<length;i++){
    
            // If there is repetition   be nums[nums[i]] == nums[i]
            while(nums[nums[i]] != i){
    
                // After exchanging data , Found duplicate , Then return to 
                if (nums[i] == nums[nums[i]]) {
    
                    return nums[i];
                }
                swap(nums,nums[i],i);
            }
        }
        return -1;
    }
    public void swap(int[] nums,int left,int right){
    
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231732009851.html