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

问题

题目:[剑指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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值