Leetccode 136 Singlenumber I
Given an array of integers, every element appears twice except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
1. I think of the first sort, and then iterate over the array to find, the complexity of the higher
2. Refer to other ideas, the best is to use the XOR, see the code
Importjava.util.Arrays; Public classS136 { Public intSinglenumber (int[] nums) { //AC but not good/*Arrays.sort (nums); int i = 0; for (; i<nums.length-1;i+=2) {if (nums[i]!=nums[i+1]) {return nums[i]; }} return nums[i];*/ //the magic of the best one xor operation 1.a^b = = B^a 2.0^a = = a if(nums.length<1) return0; intRET = Nums[0]; for(inti = 0;i<nums.length;i++) {ret= ret^Nums[i]; } returnret; }}
Leetccode 137 Singlenumber II
Given an array of integers, every element appears three times except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
1. Using sort and traverse can also be AC
2. Use XOR, see Code
Public classS137 { Public intSinglenumber (int[] nums) { //AC but not good/*Arrays.sort (nums); int i = 0; for (; i<nums.length-1;i+=3) {if (nums[i]!=nums[i+1]) {return nums[i]; }} return nums[i];*/ //a general algorithm intA[] =New int[32]; intRET = 0; for(inti = 0;i<32;i++){ for(intj = 0;j<nums.length;j++) {A[i]+ = (nums[j]>>i) &1; } ret|= (a[i]%3) <<i; } returnret; }}
Leetccode 260 Singlenumber III
Given An array of numbers nums
, in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the 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. The above example, is
[5, 3]
also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Idea: The results of all elements will be different or get the result ret is definitely not zero, and then shifted to find the first non-zero bits, record position pos. The array is then iterated, all POS locations are zero-NUM1, and all POS locations are of one or num2,num1 and num2 are answer. Because the non-zero bits in RET is the corresponding bit is NUM1 and num2 corresponding bit XOR, must be NUM1 and num2 this bit different, the array is divided into two groups respectively or is actually the first case of the solution. See Code
Public classS260 { Public int[] Singlenumber (int[] nums) { intnum1= 0,num2 = 0; intRET = 0; for(inti = 0;i<nums.length;i++) {ret^=Nums[i]; } intpos = 0; for(;p os<32;pos++){ if((ret>>pos&1) = = 1){ Break; } } for(inti = 0;i<nums.length;i++){ if((nums[i]>>pos&1) ==1) {NUM1^=Nums[i]; }Else{num2^=Nums[i]; } } intRets[] ={num1,num2}; returnRETs; }}
Leetccode 136 137 260 singlenumber I II III