《leetCode》:Single Number III

来源:互联网 发布:国家与地区顶级域名 编辑:程序博客网 时间:2024/06/03 06:38

题目

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
原创粉丝点击