1.数组中重复的数字

数组中重复的数字

1.题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

2.思路

从头到尾依次遍历数组,比较下标为i的数字(用m表示)是否等于i。如果相等则遍历下一个数字,否则比较m和下标为m的数字是否相等,相等则找到了一个重复数字,返回true,否则交换m和下标为m的数字,把m放到下标为m的位置。重复这个过程,直到找到重复的数字

3.代码

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(numbers == NULL || length <= 0){
            return false;
        }
        for(int i = 0;i < length;++i){
            while(numbers[i] != i){
                if(numbers[i] == numbers[numbers[i]]){//比较下标为i的数字(几位m)和下标为m的数字是否相等
                    *duplication = numbers[i];
                    return true;
                }
                else{
                    swap(numbers[i],numbers[numbers[i]]);
                }
            }
        }
        return false;
    }
};

4.复杂度分析

时间复杂度:有一个两重循环,但每个数字最多交换两次就能找到属于它自己的位置,因此总的时间复杂度是O(n)
空间复杂度:O(1)

发布了71 篇原创文章 · 获赞 0 · 访问量 811

猜你喜欢

转载自blog.csdn.net/jiangdongxiaobawang/article/details/103909957
今日推荐