Offer surface prove safety questions 3 (java version): the array duplicate numbers

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91382664

welcome to my blog

3_ array face questions duplicate numbers

image

Thinking

  • By one position determination, to the current position, or numbers [i] == i;! Or numbers [i] = i
  • ! If numbers [i] = i, or numbers [numbers [i]] == numbers [i], returns to true;! Or numbers [numbers [i]] = numbers [i], index i and index exchange numbers [ i] corresponding to the value of
  • After all the positions been traversed if not returns true, then there is no duplicate numbers, return false

the complexity

  • Time complexity: Although the two cycles, but will be able to exchange a maximum of two numbers each in the correct position, the time complexity is O (n)
  • Space complexity: no use of additional memory space, the space complexity is O (1)
public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        // 健壮性判断
        if(length <= 0)
            return false;
        for(int i = 0; i<length; i++){
            if(numbers[i] > length - 1 || numbers[i] < 0)
                return false;
        }
        // 正式判断, 逐个位置处理
        for(int i = 0 ; i < length; i++){
            while(numbers[i] != i){ // 直到把索引i的位置处理正确后才调出循环
                int m = numbers[i];
                if(m == numbers[m]){
                    duplication[0] = m;
                    return true;
                }
                // swap
                int temp = numbers[i];
                numbers[i] = numbers[m];
                numbers[m] = temp;
            }
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91382664