Leetcode Practice-singlenumber

Source: Internet
Author: User

Topic Meaning:

In a numeric array, most of the values appear two times, and only one value appears once, and the number is calculated for programming.
Requirements, the time complexity is linear, the space complexity is O (1).

Problem Solving Ideas:

1. First sort, then find.

Because the quickest time to sort is O (Nlogn), this method does not meet the time requirement.

2. Other tricks to solve:

According to the basic principle of computer composition of knowledge, using "XOR operation" to skillfully complete,

The XOR operation is simple:

0^0=0
1^1=0
1^0=0^1=1

That is to say, the same is 0, and the difference is 1.

So any difference or operation value of the same two number is 0.

0 An XOR operation equals the value of any number.

So, all we need to do is to make an XOR operation (O (N)) for all the numbers, and the result is the value we're looking for, only once.

#include <iostream>#include <vector>using namespace STD;//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?classSolution { Public:intSinglenumber ( vector<int>& Nums) { vector<int>:: Iterator it; It=nums.begin ();intSum=*it; for(It=nums.begin () +1; It<nums.end (); it++) {sum=sum^ (*it); }returnSum }};intMain () {Solution instance = solution (); vector<int>NumsSTD:: vector<int>:: Iterator it; it = Nums.begin ();intT while(Cin>>t) {It =nums.insert (it,t); }cout<< Instance.singlenumber (nums) << Endl;return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode Practice-singlenumber

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.