Single number II Total accepted: 20813 total submissions: 62103my submissions
Given an array of integers, every element appears three times must t for one. Find that single one.
Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?
Discuss
Because all other numbers appear three times, the sum of 1 on the nth bit of all numbers must be a multiple of 3, or % 3 is 1. Because if there is no single number, the sum of 1 on the nth bit of all numbers must be a multiple of 3. After a single number is added, if the number is 1 on this, the sum of % 3 is 1. Otherwise, if the value is zero, it is a multiple of 3.
It applies to all other numbers that appear n> = 3 times, and only one number appears once.
public class Solution { public int singleNumber(int[] A) { int arr[] = new int[33]; //and the number on every bit,and add the bits for(int i=0;i<=31;i++) { int bit = 1<<i; // the bits is 2^31 for(int j=0;j<A.length;j++) { // this must be unequal, not bigger than if((A[j]&bit)!=0) { arr[i]++; } } } int res = 0; // reconstruct the number for(int i=0;i<=31;i++) { if(arr[i]%3!=0) { res += 1<<i; } } return res; }}