Sword refers to Offer 03. Repeated numbers in the array-Java

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof

Method 1: Traverse the array

Since we only need to find any repeated number in the array, we traverse the array and return when it encounters a repeated number. In order to judge whether a number is encountered repeatedly, a set is used to store the number that has been encountered. If a number encountered is already in the set, the current number is a repeated number.

  1. Initialize the collection to an empty collection
  2. Traverse each element in the array and add the element to the collection to determine whether the addition is successful
  3. If the addition fails, it means that the element is already in the collection, so the element is a repeating element
//Set集合
public static int findRepeatNumber(int[] nums) {
    
    
Set<Integer> set = new HashSet<>();
    for (int num : nums) {
    
    
    	//添加num到set集合中,若添加失败,返回num
        if (!set.add(num)) {
    
    
            return num;
        }
    }
     //没有重复元素,返回-1
    return -1;
}
//Map集合
public static int findRepeatNumber(int[] nums) {
    
    
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int num : nums) {
    
    
    	//如果Map集合中没有num,就把num存入集合
        if (map.get(num) == (null)) {
    
    
            map.put(num, 1);
        } else {
    
    
        //否则,返回num
            return num;
        }
    }
    //没有重复元素,返回-1
    return -1;
}

Method 2: Sort first and find

After sorting, the duplicates must be next to each other, and then compare them before and after. If there are duplicates, return directly

public static int findRepeatNumber(int[] nums) {
    
    
    Arrays.sort(nums);
    for (int i = 1; i < nums.length; i++) {
    
    
        if (nums[i] == nums[i - 1])
            return nums[i];
    }
    return -1;
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/107597421