Leetcode:single-number-ii (Java bit operation)

Source: Internet
Author: User

Topic:

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?

Given an array of integers, each number appears three times (only one occurrence of a number), and the number that appears only once is found. Requirements: Time complexity O (n), Spatial complexity O (1). This type of problem is usually solved using bit arithmetic.

The solution 1:int data has 32 bits, which can be stored with 32 variables: The number of occurrences of "1" on each bits of this n element. Finally, the "modulo 3" operation, if 1, that means that this bit is to find the number binary representation of the 1 of the One

Class Solution {public  :      int singlenumber (int a[], int n) {          int bitnum[32]={0};  Use an array of bitnum to hold an int array n elements        int res=0;          for (int i=0, i<32; i++) {for              (int j=0; j<n; J + +) {                  bitnum[i]+= (a[j]>>i) &1;               Each element in the array is bitnum to 1, and the result of the operation is superimposed on the I-bit            }              res|= (bitnum[i]%3) <<i;  The superimposed result modulo 3 operation is determined Bitnum[i]        }          return res;  After the loop, get each element of the Bitnum array, the Bitnum array is the one that appears only once    }  };  

Solution 2: This is a faster solution, using three variables to save each bits 1 appears once, twice, three times the distribution, and finally just return the variable one on the line.

Class Solution {public  :      int singlenumber (int a[], int n) {          int one=0, two=0, three=0;          for (int i=0; i<n; i++) {              |= one&a[i];              One^=a[i];              cout<<one<<endl;              three=one&two;              one&= ~three;              two&= ~three;          }          return one;      }  ;  

Explanation: Each cycle first calculates the twos, namely appears two times 1 the distribution, then calculates the occurrence 1 the distribution, then the two carries on and the operation obtains three times the distribution of 1, then carries on the inverse to the threes, then with the ones, twos and the operation, so the goal is to appear three times the position to clear zero. Although this method is faster and more space-saving, it is not universal.

Similar questions:

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?

Class Solution {public:    int singlenumber (int a[], int n) {        int res=0;        for (int i=0;i<n;i++) {            res=res^a[i];        }        return res;    }};
bit operations in JavaA bitwise operator is defined in Java, and is applied to types such as Integer type (int), long integer, short, character (char), and byte type (byte). The bitwise operator acts on all the bits, and the bitwise operation. The bitwise operators are evaluated in binary format, that is, if the given number format is not binary format it needs to be converted to binary format first.Common bitwise operators1. With operatorAnd the operator is denoted by the symbol "&", its use is as follows: two operand median is 1, the result is 1, otherwise the result is 0, for example, the following program segment.

public class Data13
{
public static void Main (string[] args)
{
int a=129;
int b=128;
System.out.println ("A and B" with the result is: "+ (a&b));
}
}
Run results
A and B with the result is: 128
The following analysis of this program:
The value of "a" is 129, converted to binary is 10000001, and the value of "B" is 128, converted to binary is 10000000. According to the operator's operation Law, only two bits are 1, the result is 1, you can know the result is 10000000, that is, 128.

2. Or operator

Or operator with the symbol "|" , its operation law is as follows: Two bit as long as one is 1, then the result is 1, otherwise 0, see a simple example below.

public class Data14
{
public static void Main (string[] args)
{
int a=129;
int b=128;
System.out.println ("A and B" or the result is: "+ (a|b));
}
}
Run results
A and B or the result is: 129
The following analysis of this program segment:
The value of a is 129, the conversion to binary is 10000001, and the value of B is 128, converted to binary is 10000000, according to the operator's operation Law, only two bits have a 1, the result is 1, you can know the result is 10000001, that is 129.

3. Non-operator
The non-operator is denoted by the symbol "~", and its Operation law is as follows: If the bit is 0, the result is 1, if the bit is 1, the result is 0, see a simple example below.

public class Data15
{
public static void Main (string[] args)
{
int a=2;
SYSTEM.OUT.PRINTLN ("A non-result is:" + (~a));
}
}

4. Xor operator

The XOR operator is denoted by the symbol "^", and its Operation law is: two operands of the bit, the same result is 0, different results are 1. Let's look at a simple example.

public class Data16
{
public static void Main (string[] args)
{
int a=15;
int b=2;
System.out.println ("A and B xor the result is:" + (a^b));
}
}
Run results
The result of A and B xor is: 13
Analysis of the above program segment: The value of a is 15, converted to binary 1111, and the value of B is 2, converted to binary 0010, according to the different or the Operation law, can be derived from the result of 1101 is 13.

Leetcode:single-number-ii (Java bit operation)

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.