数组中重复的数字

题目

链接:https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

**Level: ** 剑指offer

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

Note:

  • 时间限制:1秒 空间限制:32768K

代码

class Solution {
public:
    bool duplicate(int numbers[], int length, int* duplication) {
        int num=0;
        for(int i=0;i<length;i++)
            numbers[i]++;
        for(int i=0;i<length;i++)
        {
            int temp = numbers[i];
            if(temp<0)
                temp*=-1;
            if(numbers[temp-1]<0)
            {
                duplication[0] = -1*numbers[temp-1]-1; 
                return true;      
            }
            else
                numbers[temp-1]*=-1;       
        }
        return false;
    }
};

思考

  • 时间复杂度为O(N),空间复杂度为o(1)
  • 因为数组中存在零元素,取负进行标记的方法会有问题,那么可以直接将数组各元素加一,然后再进行取负标记。
原文地址:https://www.cnblogs.com/zuotongbin/p/10220465.html