Duplicate arrays of numbers (to prove safety offer_3)

All numbers in a length of n in the array are in the range 0 to n-1. Some digital array is duplicated, but do not know how many numbers are repetitive and do not know each digit is repeated several times. Please find an array of any one of the duplicate numbers.

Input:

{2,3,1,0,2,5}

Output:

2

Problem-solving ideas:

Required time complexity O (N), the spatial complexity is O (1). Sorting method could not be used, you can not use the additional array of tags.

For solving this array element [0, n-1] the problem range, the element can be adjusted to a value i of i-th position. This question asked to find duplicate numbers, so the adjustment process, if the element has a value of i is the i-th position, can know the value of i is repeated.

In (2,3,1,0,2,5) as an example, to traverse the 4 position, this position is the number 2, but has a value of 2 in the second position, the guide can be repeated 2 :

 

 

 

public boolean duplicate(int[] nums, int length, int[] duplication) {
    if (nums == null || length <= 0)
        return false;
    for (int i = 0; i < length; i++) {
        while (nums[i] != i) {
            if (nums[i] == nums[nums[i]]) {
                duplication[0] = nums[i];
                return true;
            }
            swap(nums, i, nums[i]);
        }
    }
    return false;
}

private void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
}

Guess you like

Origin www.cnblogs.com/ziytong/p/12079747.html