Single Number III

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值