Leetcode: single number II

Source: Internet
Author: User

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?


The question is clear, with emphasis on the extra space of Linear Time and constants. Single number I refers to the difference or, finally, the answer. But here there are three, what should I do?

When there are three times, if we still start with bitwise operations, what are the features? Set the unique number to X. The feature is that it is measured in 32 bits of the int type. Assume that X is 0 on this bit, then it should be that the number of occurrences of the bit 1 is a multiple of 3, and if it is 1, it should be 1 of the occurrence of the 3N + 1. According to this feature, to calculate the unique data;

Set three intors, one, two, and three. Here, a value of 0 is displayed. Once it is set to 0, twice, once it is set to 1, and once it is set to 1, the high value here exists in two, and the low value exists in one, perform operations according to different States. At the same time, 0 is cleared for 1. here, one represents the low-level count of each bit, and two represents the High-Level count of each bit;

 
Public: int singlenumber (int A [], int N) {int one = 0, two = 0, three = 0; For (INT I = 0; I <N; I ++) {two | = one & A [I]; // be careful one ^ = A [I]; three = one & two; one & = ~ Three; two & = ~ Three;} return one ;}

Here, be careful two can use exclusive or, because it is impossible for one two to have the same bit at the same time, so the exclusive or the same, but logically, it should be optional or, better represents the meaning of this algorithm;

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.