Single Number Ⅰ:
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 class Solution { public int singleNumber(int[] nums) { if(nums.length == 1){ return nums[0]; } for(int i = 1; i < nums.length; i++){ nums[0] = nums[0] ^ nums[i]; } return nums[0]; } }
代码:
public class Solution { public int singleNumber(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); for(int n : nums){ if(!set.add(n)){ set.remove(n); } } Iterator<Integer> it = set.iterator(); return it.next(); } }
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 class Solution { public int singleNumber(int[] nums) { int [] numsOfBits = new int[32]; int res = 0; for(int i = 0; i < 32; i++){ for(int j = 0; j <nums.length; j++){ numsOfBits[i] += (nums[j] >> i) & 1; } res |= (numsOfBits[i] % 3) << i; } return res; } }
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:
[5, 3]
is also correct.代码:
public class Solution { public int[] singleNumber(int[] nums) { int result[] = {0,0}; int temp = nums[0]; for(int i = 1; i < nums.length; i++){ temp = temp ^ nums[i]; } int difference = temp & (~(temp - 1)); for(int i = 0; i < nums.length; i++){ if((difference & nums[i]) == 0){ result[0] = result[0] ^ nums[i]; }else{ result[1] = result[1] ^ nums[i]; } } return result; } }
int difference = temp & (~(temp - 1));这条语句表示取出两个数最小的不同位用来分割数组。