Single Number III

来源:互联网 发布:知福茶叶公司 编辑:程序博客网 时间:2024/04/28 18:10

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?


思路

刚好昨天看了下编程之美,异或,然后结果有1的那一位,肯定二者不同的,所以分组

这样两次线性的扫描就ok

思路是对的,但是在写代码的时候,还是有问题,就是这个分组怎么具体实现

然后用c语言的时候,要注意在里面分配空间,因为传入的是指针


位运算


  1. a^b=c c^a=b这是可逆的,所以不需要分两组,直接用逆运算就可以了

  2. 分组的flag怎么得到,然后if语句判断怎么实现

  1. flag = x & -x; //Get last bit of x
    for (i = 0; i < numsSize; i++)
    if ((tmp = nums[i]) & flag) y ^= tmp;
    ret[0] = x ^ y;
    ret[1] = y;


  2. /*flag is the last "1" bit of n,the two elements which appear only once must be defferent in this bit
    so we can use flag to devide all the elements into two parts,one contains a and the other one contains b.*/
    int flag = n & (~(n - 1));
    if((flag&nums[i]) == 0) a ^= nums[i];


    flag = n & (~(n - 1)这个,最后一位1的位置为1,其余都是0
    eg 0011 flag就是0001


代码

/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* singleNumber(int* nums, int numsSize, int* returnSize) {    if (!nums || (numsSize < 2)) return NULL;    int * result;    result = (int *)malloc(sizeof(int)*2);    if(result)    {        int i;        int sum=0;        int flag;        for(i=0;i<numsSize;i++)        {           sum ^= nums[i];        }        flag = (sum & ~(sum-1));        result[0] = 0;result[1] = 0;        for(i=0;i<numsSize;i++)        {            if((nums[i]&flag) == 0)                 result[0]^=nums[i];        }        result[1] = sum ^ result[0];        * returnSize = 2;    }    return result;}


大写加粗的注意

  1. if((nums[i]&flag) == 0)
    这里以一定要有括号
    == 优先级比 & 高

  2. if(result)
    这里细节是判断分配空间是否成功

  3. if (!nums || (numsSize < 2)) return NULL;
    这里细节是判断参数是否有效
0 0
原创粉丝点击