《剑指offer》-----------------数组中重复的数字

题目

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

方法一

数组中的所有数字都为0到n-1,可以把这些数字当做数组下标,数值用来统计个数,即i为下标,map[i]为个数,如果map[i]r>1,则i为相应的重复数字。例如数组numbers[5]={1,2,4,2,5}
设定map[255]={0};numbers[0]=1;map[1]++;
numbers[1]=2;则map[2]++;
到numbers[3]=2时。则map[2]++。此事map[2]为2.则代表有两个重复的数字。

代码

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) {
    /*错误判断省略*/
    int map[255] = {0};
    for (int i = 0; i < length; i++)
    {
        map[numbers[i]]++;
    }
    for (int i = 0; i < length; i++)
    {
        if (map[i] > 1)
        {
            *duplication = i;
            return true;
        }
    }
    return false;
}
};

方法二

书中的思路是对于数组中第i个数,先判断它(n[i])是否等于i,相等则不作处理(即第i个数为i),不相等则判断这个数(n[i])对应的数组中第n[i]个数(n[n[i]])是否和它相等,不相等则交换他们,交换过后,第n[i]个数为n[i]。
将当前的数字和当前数字索引下的数字进行比较,如果不同就交换,直到访问的数字和该数字索引下的数字相等(不和当前的索引相同),便是第一个重复数字,如果将数组都遍历一遍了的话,就意味着没有重复数字。

以[1,3,2,0,2,5,3]举例

首先,遍历到数字1,数字1不等于当前索引0,且和numbers[1]也不相同,所以根numbers[1]的数字交换,当前数组为[3,1,2,0,2,5,3]。

由于3还是不等于0,再根numbers[3]交换,当前数组为[0,1,2,3,2,5,3].

由于0和当前索引0相同,扫描下一个数字,1和索引1相等,以此类推,直到扫描到numbers[4],也就是2,此时2不等于当前索引4,比较numbers[2]的数字恰好等于2,意味着这个元素是访问过的,这样便找到了第一个相同的元素。

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) {
        int temp;
        for(int i=0;i<length;i++)
        {
            while(true)
            {if(numbers[i]==i)
                break;
            if(numbers[i]!=i)
            {
                if(numbers[i]==numbers[numbers[i]])
                {
                    *duplication=numbers[i];
                    return true;
                }
                else
                {
                    temp=numbers[i];
                    numbers[i]=numbers[temp];
                    numbers[temp]=temp;
                }
            }
        }
        
           
        } 
        return false;
    }
};
发布了47 篇原创文章 · 获赞 2 · 访问量 1442

猜你喜欢

转载自blog.csdn.net/weixin_42076938/article/details/104248266