The sword refers to the Offer-question 3: Find the repeated numbers in the array

Question: Find Repeating Numbers
in an Array In an array of length n all numbers are in the range 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, and I don't know how many times each number is repeated. Find any repeated number in the array. For example, if the input array is {2, 3, 1, 0, 2, 5, 3} of length 7, then the corresponding output is the repeated number 2 or 3.

The main idea: the range of numbers in the array is 0~n-1. If there are no repeated numbers, the number i appears in the position subscript i in the array after sorting. However, because there are repeated numbers, there is no one-to-one correspondence between numbers and their subscripts. Rearrange the array (numbers), scan from the beginning to the end, when the subscript i is scanned, determine whether its value (m) is equal to i. If equal, continue to scan the next position. If they are not equal, the value m is compared with the value with subscript m (numbers[m]), and if the two numbers are equal, the first repeated number is found (the number in the subscript i and m). positions appear); if they are not equal, swap the positions of the two numbers so that the value m is equal to its subscript. Next continue comparing swaps until a duplicate number is found.

Key point: Find the relationship between the value and its index.

Time complexity : O(n)

public class DuplicateNumber
{
    public static void main(String[] args)
    {
        int numbers[] = {2, 3, 1, 0, 2, 5, 3};
        int[] duplications = new int[numbers.length];
        boolean isDuplicated = duplicate(numbers, numbers.length, duplications);
        if(isDuplicated)
        {
            System.out.println(duplications[0]);
        }
    }

    private static boolean duplicate(int numbers[], int length, int[] duplication)
    {
        if (numbers == null || length <= 0) return false;
        //判断输入数组是否正确
        for (int i = 0; i < length; i++)
        {
            if (numbers[i] < 0 || numbers[i] > length - 1)
            {
                return false;
            }
        }
        for (int i = 0; i < length; i++)
        {
            //循环直到数值和下标相等
            while (numbers[i] != i)
            {
                int currentNumber = numbers[i];
                //该数字出现两次
                if (currentNumber == numbers[currentNumber])
                {
                    duplication[0] = currentNumber;
                    return true;
                }
                //交换
                int temp = numbers[currentNumber];
                numbers[currentNumber] = currentNumber;
                numbers[i] = temp;
            }
        }
        return false;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599430&siteId=291194637