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