Leetcode: Single number Iii_leetcode

Source: Internet
Author: User
Tags diff

Given An array of numbers nums, in which exactly two elements-appear only once and all the other elements appear exactly t Wice. Find the two elements this appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the ' is ' not important. The above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

For the given array, except for two numbers, the other numbers appear two times and find the two numbers that occur once.

Idea: In fact, as with single number, just add a trick, first to store all the difference or the results, then this number must be the occurrence of 1 of the two number of differences or results. In the binary representation of the result, a bit with a value of 1 must be a different bit of these two numbers, such as 3 (011) and 5 (101), with two digits. This means that there must be a certain one, a number at which the value is 1 and the other is 0. So we can divide the number of the original array into two groups, and use single number to find out the two numbers.

Code:

 public class Solution {public int[] Singlenumber (int[] nums) {if (Nums = null | | nums.length = 0) {
        return null;

        int diff = 0;
        for (int num:nums) {diff ^= num;

        Diff &=-diff;

        Int[] result = new INT[2];
            for (int num:nums) {if ((num & diff) = = 0) {result[0] ^= num;
            }else{result[1] ^= num;
    } return result; }
}

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.