49 数组中重复的数字 记忆

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思路:1)直接排序;
           2)使用哈希表,比如开辟一个布尔数组,判断该数字在之前是否已经访问过,vector<bool> visit(n,false);已经访问过,则找到这个重复数字。
   3)时间复杂度是O(n),空间复杂度是O(1),这个数组的特点是里面的元素都是0-n-1之间的数字,如果排好序之后,应该是每个位置上的元素都和下标相等。
依次扫描这个数组中的元素,对于下标i对于的元素为m,如果m != i,那么就将下标为m的元素和下标为i的元素进行交换,直到下标和对应的元素相等为止。
理解难点1:何时退出循环,记得numbers[i] != i有可能遇到211,这种根本没有0的情况,那么肯定会第二个循环陷入死循环,这种情况就需要在里面做出一个if判断,不应该在while循环外面进行if判断,因为如果是有序的012,numbers[numbers[i]] == numbers[i],那么找到的就不是想要的结果。
理解难点2:复杂度有两个for循环,但是为什么时间复杂度是O(n)?
摊还分析:每个元素最多交换两次,所以复杂度是O(n)。举个例子就知道,第一次被交换到某个位置的num,第二次会作为下标,肯定交换到对应位置,所以最多是交换两次。
class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
        if(length <= 0){
            *duplication = -1;
            return false;
        }
        for(int i = 0;i < length;++i){
           //必须首先判断 numbers[i] != i,不然考虑已经排好序的情况,0,1,2,3,4,i= 1,numbers[1] = 1;
            //肯定numbers[numbers[i]] == numbers[i],
            while(numbers[i] != i){//可能2,1,1这种没有0的情况,那么就会
                if(numbers[numbers[i]] == numbers[i]){
                    *duplication = numbers[i];
                    return true;
                }
                swap(numbers[i],numbers[numbers[i]]);
            }
        }
        *duplication = -1;
        return false;
    }
};

 

 
posted @ 2018-01-13 14:20  zqlucky  阅读(168)  评论(0编辑  收藏  举报