您的位置:首页 > 其它

260. Single Number III

2016-08-11 07:36 134 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: