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

来源:互联网 发布:多玩tbc数据库 编辑:程序博客网 时间:2024/06/05 00:30

问题

题目:[剑指offer-数组中重复的数字]

思路

这个题我觉得其实它也没说清楚,看了注释才明白。
要得到所有重复的数字。
那我就判断一下,第一次重复数字出现的时候得到,通过first标记来判断是不是第一次。

代码

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) {        sort( numbers, numbers + length );        int sz = length;        int k = 0;        int first = 1;        for(int i = 1; i < sz; ++i){            if( numbers[i-1] == numbers[i] && 1 == first ){                duplication[k++] = numbers[i];                first = 0;            }            else if( numbers[i-1] != numbers[i]) first = 1;        }        return k > 0;    }};

思路1

参考了下这篇链接:[(剑指Offer)面试题51:数组中重复的数字]

发现自己在做的时候,对题目的理解不正确。
题目的意思是判断数组中是否存在重复的数字,如果有重复的,返回第一个重复的就可以了。

这么考虑,如果没有重复的。那么肯定是a[i] = i;这种情形。如果有,就不是了。

所以,对于任意一个位置i,判断a[i] == i,如果相等,则没事。
如果,不相等,则loc = a[i],也即a[i]应该在loc的位置上。那么判断,a[i] == a[loc],则证明已经有重复元素。返回true。否则,交换。这样可以保证a[loc] == a[i],即loc存储的是本生的元素。对于a[i],继续判断。

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 || length < 1 || !duplication ) return false;        for(int i = 0; i < length; ++i){            while( numbers[i] != i ){                int loc = numbers[i];                if( numbers[i] == numbers[loc] ){                    *duplication = numbers[i];                    return true;                }                std::swap( numbers[i], numbers[loc] );            }        }        return false;    }};
原创粉丝点击