《leetCode》:Single Number III

题目

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

思路

这个题在《剑指Offer》上面遇到过,现在又忘了如何来做的思路。思路的连接在这里:http://blog.csdn.net/u010412719/article/details/49080795

又实现了一遍,代码如下:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
/*
http://blog.csdn.net/u010412719/article/details/49080795
思路:既然我们知道如何从只有一个数出现一次其他数出现两次的数组中得到这个数。
因此,我们就应该想办法将这两个数分到两个子数组中,且保证子数组中其它的每个数都出现了两次。 
*/
/*
函数的功能:判断数字 num在第 index比特位是否为1 
*/
bool isBitOne(int num,int index){
    if((num>>index)&0x01){
        return true;
    } 
    return false;
}
int* singleNumber(int* nums, int numsSize, int* returnSize) {
    if(nums==NULL||numsSize<1){
        return NULL;
    }
    //第一步:得到两个不同的数的异或值 
    int aXorB=0;
    for(int i=0;i<numsSize;i++){
        aXorB^=nums[i];
    }
    //第二步:根据异或值的结果中最右边的1将nums分成两个子数组。
    int oneBitIndex=0;
    while(aXorB){
        if(aXorB&0x01){
            break;
        }
        aXorB>>=1;
        oneBitIndex++;
    } 
    *returnSize=2; 
    int *res=(int *)malloc((*returnSize)*sizeof(int));
    if(res==NULL){
        exit(EXIT_FAILURE);
    }
    memset(res,0,(*returnSize)*sizeof(int));
    int secondRes=0;
    for(int i=0;i<numsSize;i++){
        if(isBitOne(nums[i],oneBitIndex)){
            res[0]^=nums[i];
        }
        else{
            res[1]^=nums[i];
        }
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值