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语言的时候,要注意在里面分配空间,因为传入的是指针
位运算
a^b=c
c^a=b
这是可逆的,所以不需要分两组,直接用逆运算就可以了
- 分组的flag怎么得到,然后if语句判断怎么实现
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;
/*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;}
大写加粗的注意
- if((nums[i]&flag) == 0)
这里以一定要有括号
== 优先级比 & 高
- if(result)
这里细节是判断分配空间是否成功
- if (!nums || (numsSize < 2)) return NULL;
这里细节是判断参数是否有效
0 0
- Single Number III
- Single Number III
- [LeetCode] Single Number III
- [leetcode] Single Number III
- 260 Single Number III
- [Leetcode]Single Number III
- [leetcode] Single Number III
- Leetcode: Single Number III
- 260 Single Number III
- LeetCode || Single Number III
- Single Number III
- Single Number III
- Single Number III
- [刷题]Single Number III
- Single Number III
- Leetcode75: Single Number III
- leetCode---Single Number III
- *LeetCode-Single Number III
- 闭包漫谈(从抽象代数及函数式编程角度)
- 关于多组输入的若干总结
- SetCapture()和ReleaseCapture()
- MySQL索引背后的数据结构及算法原理
- TextView属性详解(转载,用的时候瞄一眼)
- Single Number III
- mount 详解
- Android Studio问题解决系列—Resources中getDrawable(int)过时
- .net 確認對話框
- Qt中编译出现mainwindow.obj:-1: error: LNK2019: unresolved external symbol "public: __thiscall MyWidget::M
- C运行时库(C Run-time Library)详解
- Android Studio问题解决系列—iCCP: Not recognizing known sRGB profile
- Imageloader 加载listview 头像 闪动,重复加载等问题的解决方案之一
- 一致性哈希算法及其在分布式系统中的应用