Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
第一题比较简单,直接逐个异或得到的结果就是唯一一个出现一次的数:
public int singleNumber(int[] nums) { int xor=0; for(int i=0;i<nums.length;i++) { xor^=nums[i]; } return xor; }
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
public int singleNumber(int[] nums) { int result=0; for(int i=0;i<32;i++) { int count=0; int mask=1<<i; for(int j=0;j<nums.length;j++) { if((nums[j]&mask)!=0) { count++; } } if(count%3!=0) { result|=mask; } } return result; }
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?
public int[] singleNumber(int[] nums) { int res=0; for(int i=0;i<nums.length;i++) res^=nums[i]; int xor=res&-res; int a=0,b=0; for(int num:nums){ if((num&xor)==0) a^=num; else b^=num; } return new int[]{a,b}; }