找出缺少的数

There is an array of size 50 that is expected to contain all the numbers from 1 to 50
(every number occuring only once). But there is one number in the array that does not
satisfy this condition i.e. one number is either duplicate or outside 1 to 50 range. 

Find the correct number that is missing in the array


方法1:


设原数组是a[],设非法的那个数是y,缺少的数是x

1+2+...+50 - sum(a) = y -x

1^2+ 2^2 + ... + 50^2 - (a[0]^2 + ...+a[49]^2) = y^2 - x^2 

可以计算出x


将数放到其应该在的地方

方法2(思想就是在位置i将其放在正确的位置):

int findMissing(int a[], int n)
{
        int i;
        for(i = 0; i < n; i++) {
                while(a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i])//短短几句话,自己写错了好多。1. 用if 不用while, 不会把数字放在其正确的位置;2. a[i] != i+1, 如果遇到重复的数字,可能会进入死循环
                        swap(a[i], a[a[i] - 1]);
        }
        for(i = 0; i < n; i++)
                if(a[i] != i + 1)
                        return i + 1;
        return -1;
}

方法3:(有点小错误)(和上个思路类似,但是,有点递推的思想)

int FindDup(int a[], int n)
{
        assert(a && n > 0);

        for (int i = 0; i < n; i++)
        {
                if (i + 1 == a[i])
                        continue;

                int nTmp = a[i];
                while (i + 1 != nTmp)
                {
                        if (nTmp < 1 || nTmp > n)
                                return -1;

                        if (nTmp == a[nTmp - 1])
                                return nTmp;

                        int x = a[nTmp - 1];
                        a[nTmp - 1] = nTmp;
                        nTmp = x;
                }
        }

        return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值