260. Single Number III
2016-08-11 07:36
134 查看
1、来源:点击打开链接
2、内容
Given an array of numbers
the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
Note:
The order of the result is not important. So in the above example,
also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity
3、看题时没有注意到是说有两个会只出现一次的数字,下面的代码为出现1次的数字个数没有限制(可以通过):
2、内容
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
3、看题时没有注意到是说有两个会只出现一次的数字,下面的代码为出现1次的数字个数没有限制(可以通过):
/** * 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) { int *flag=(int*)malloc(sizeof(int)*numsSize); int *result; int i,j,k; for(i=0;i<numsSize;i++) flag[i]=0; k=numsSize; for(i=0;i<numsSize;i++){ if(flag[i]==0){ for(j=i+1;j<numsSize;j++){ if(nums[i]==nums[j]){ flag[i]=1; flag[j]=1; k=k-2; break; } } } } result=(int*)malloc(sizeof(int)*k); k=0; for(i=0;i<numsSize;i++){ if(flag[i]==0){ result[k]=nums[i]; k++; } } *returnSize=k; return result; }4、参考别人的思路后(点击打开链接):
/** * 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) { int i,s,flag; *returnSize=2; s=0; for(i=0;i<numsSize;i++) s^=nums[i]; flag=1; while((s&flag)==0){ flag=flag<<1; } int *result=(int*)malloc(8); result[0]=0; result[1]=0; for(i=0;i<numsSize;i++){ if((flag&nums[i])==0){ result[0]^=nums[i]; } else result[1]^=nums[i]; } return result; }
相关文章推荐
- 260. Single Number III
- 260. Single Number III
- LeetCode笔记:260. Single Number III
- 260.Single Number III
- [LeetCode]260. Single Number III
- 260. Single Number III
- LeetCode *** 260. Single Number III
- leetcode 260. Single Number III-寻找单身狗|位运算
- 260. Single Number III
- leetcode 260. Single Number III --> 用hashmap计算出现的次数,注意containsKey获取key,用 get 方法获取值
- 260. Single Number III
- [LeetCode] 260. Single Number III(位操作)
- leetcode 260. Single Number III 神奇的位操作 + 找到两个只出现一次的数
- 260. Single Number III
- 260. Single Number III -取出非重复数字(加强版)
- [LeetCode] 260. Single Number III 单独数 III
- LeetCode 260. Single Number III
- [LeetCode] 260. Single Number III(位操作)
- 260. Single Number III
- leetcode 260. Single Number III