LeetCode#287. Find the Duplicate Number

Keywords: less

  • Title: An array of size n+1 with elements between 1 and N (including 1 and n). Assuming that there is only one repeating element in the array (the repetition number may be 2, 3, or more), find out the repeating element.
  • Difficulty: Medium
  • Idea: Based on binary search, find the middle table mid below the array, traverse the count of the number of arrays whose value is less than or equal to mid.
    • If count is less than or equal to mid, it means that the value of duplicate elements is between 1 and mid (that is, the search space is reduced to [1, mid].
    • If count is greater than mid, the repetitive element values are between mid+1 and nums.length-1.
      Repeat the above steps until there is only one element in the lookup space
  • Code:
public class Solution {
    public int findDuplicate(int[] nums) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        int left = 1;
        int right = nums.length-1;

        while(left < right){
            int count = 0;//Number of records less than mid
            int mid = left + (right-left)/2;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] <= mid){
                    count++;
                } 
            }
            if(count > mid){
                right = mid;
            }else{
                left = mid + 1;
            }
            System.out.println(count + "-" + mid);
        }
        return left;

    }
}

Method 2: Construct a linked list, using the value of array elements as a pointer, and the header node as the subscript of the last element of the array. In this way, finding duplicate elements becomes the entrance to looking for linked list rings.

public class Solution {
    public int findDuplicate(int[] nums) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        int slow = nums.length;
        int fast = nums.length;
        do{
            slow = nums[slow-1];
            fast = nums[nums[fast-1]-1];//Equivalent to two steps of chain pointer movement
        }while(slow != fast);

        slow = nums.length;
        while(slow != fast){
            slow = nums[slow-1];
            fast = nums[fast-1];
        }
        return slow;

    }
}

Posted by tam2000k2 on Sun, 10 Feb 2019 20:33:18 -0800