Single number II

Source: Internet
Author: User
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;    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.