Single Number and single number II

Source: Internet
Author: User
1 single number

Given an array of integers, every element appearsTwiceCould t for one. Find that single one.

Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?

Resolution:

A ^ A = 0, a ^ 0 =

Therefore, the final result is the difference or for all numbers.

1     public int singleNumber(int[] A) {2         int single = 0;3         for (int i : A) {4             single ^= i;5         }6         return single;7     }
View code2 single number II

Given an array of integers, every element appearsThreeTimes has t for one. Find that single one.

Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?

Resolution:

(1) A @ A = 0, a @ 0 =

You only need to find the operation function @ that satisfies the preceding equation.

(2) A-> one, a @ A-> two, a @ A-> One @ two = 0

That is, if operation a is performed, the result is recorded to one. If operation two times, the result is recorded to two. If operation three times, the result is recorded to one and two, and the result is set to 0.

 1     public int singleNumber_3(int[] A) { 2         int one = 0; 3         int two = 0; 4         for (int carry : A) { 5             while (carry != 0) { 6                 two ^= one & carry; 7                 one ^= carry;     8                 carry = one & two; 9             }10         }11         return one;12     }
View code

 

Single Number and single number II

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.