Leetcode | | 136, single number

Source: Internet
Author: User

Problem:

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?

Hide TagsHash Table Bit manipulationTest instructions: A group of numbers, only one number appears once, the other number appears two times, find out the number

Thinking:

(1) The bitwise operation, the XOR operator

0^a=a;

a^a=0;

A^b=b^a;

(2) The solution to this problem comes out: N number of different or result is to be asked

Code

Class Solution {public:    int singlenumber (vector<int>& nums) {        int n=nums.size ();        int ret=nums[0];        for (int i=1;i<n;i++)            ret^=nums[i];        return ret;                }};


Extension, refer to http://www.cnblogs.com/changchengxiao/p/3413294.html


1. There are two elements in an array that occur only once, and all the other elements appear two times, to find the two elements that appear only once

[Ideas for solving problems]

Sets all the elements of an array to be different or to get a result that is not 0, according to one of the non-0 in this result, divides the array into two groups

If the elements in the two groups are different or if the XOR value of two arrays is not 0, the final result is obtained



2. One element in an array appears only 1 times, and all other elements appear k times, asking for the element that only appears 1 times

[Ideas for solving problems]


When k is even, the same as LSS


When k is odd, add a mod k to each of the elements in the array, get the result 1 elements of the throne, Time complexity O (nlen), Space complexity O (1)

Leetcode | | 136, single number

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.