您的位置:首页 > 其它

数组中除一个元素外其他所有元素出现二或三次,找到只出现一次的元素

2016-04-01 10:13 519 查看
1、数组中除一个元素外其他所有元素出现二,找到只出现一次的那个元素。

public int singleNumber(int[] nums) {
int res = nums[0];
for (int i = 1; i < nums.length; i++)
res = res ^ nums[i];

return res;
}


2、数组中除一个元素外其他所有元素出现三次,找到只出现一次的那个元素。

public static int singleNumber(int[] nums) {
int len = nums.length, result = 0;
for (int i = 0; i < 32; i++) {
int sum = 0;
for (int j = 0; j < len; j++) {
sum += (nums[j] >> i) & 1;
}
result |= (sum % 3) << i;
}
return result;
}


3、数组中所有元素出现两次,其中有两个元素只出现一次,找出这两个元素。

public static int[] geTwoEle(int[] res){
if(res.length==2)return res;
int []val=new int[2];
int temp=res[0];
for(int i=1;i<res.length;i++){
temp^=res[i];
}
//find the leftmost pos where two element is different
int i=0;
while(temp!=0)temp>>=++i;
i--;

int left[]=new int[res.length];
int right[]=new int[res.length];
int lefti=0;
int righti=0;
//split val array into two arrays according to the different pos
for(int j=0;j<res.length;j++){
if(((res[j]>>i)&1)==0){
left[lefti++]=res[j];
}else{
right[righti++]=res[j];
}
}
//in left and right array only one element is different,use ^ to find the element
val[0]=left[0];
for(int j=1;j<lefti;j++){
val[0]^=left[j];
}

val[1]=right[0];
for(int j=1;j<righti;j++){
val[0]^=right[j];
}

return val;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息