[Rookie Training] Sword Finger Offer 03. Repeated numbers in the array (simple questions)

Title description:
Find the repeated numbers in the array.

All numbers in an array nums of length n are in the range of 0~n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, nor do I know how many times each number is repeated. Please find any duplicate number in the array.

Example 1:

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

Limit:
2 <= n <= 100000

Problem-solving ideas:
Method 1: You can use the idea of ​​a hash algorithm to exchange space for time. First, create a hash array with the same size as the known array, and use this array to record the number of occurrences of each element in the nums array. When an element appears more than once, it can be output.

//使用一个哈希算法来解决
    public int findRepeatNumber(int[] nums){
    
    
        int n = nums.length;
        int[] flag = new int[n];
        for (int i = 0; i < n; i++){
    
    
            flag[nums[i]]++;
            if(flag[nums[i]]>1){
    
    
                return nums[i];
            }
        }
        return -1;
    }

Method 2: You can use set to solve this problem. First add the first element to the HashSet object, and then traverse the nums array. If the HashSet object contains the element, return the element, otherwise add the new element to the HashSet object.
Note that in this method, you cannot use List to implement this function, and using List will cause the time limit to be exceeded.

//使用Set来做
    public int findRepeatNumber1(int[] nums){
    
    
        HashSet set = new HashSet();
        set.add(nums[0]);
        for (int i = 1; i < nums.length; i++){
    
    
            if(set.contains(nums[i])){
    
    
                return nums[i];
            }else{
    
    
                set.add(nums[i]);
            }
        }
        return -1;
    }

Guess you like

Origin blog.csdn.net/Puppet__/article/details/114973350