The sword points to the offer surface question 40: Two numbers in an array that appear only once

Source: Internet
Author: User

Interview question 40: two numbers in an array that occur only once

Submission URL: http://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193

or http://ac.jobdu.com/problem.php?pid=1351


title: in an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is o (n), and the spatial complexity is O (1).

the input and output interface of the OJ is: void Findnumsappearonce (vector<int> data,int* num1,int *num2), where data is to be found an integer array, while NUM1 and num2 are pointers to two numbers respectively, and the return value is *NUM1 and *num2, which requires the original site and the return value to be of type void.


Input:
Each test case consists of two lines: the first row contains an integer n, which indicates the size of the array. 2<=n <= 10^6. The second row contains n integers, which represent the array elements and the elements are int.
Output:
corresponding to each test case, the output array only appears once in two digits. The output of the numbers from small to large order.
Nine-degree OJ Sample input:
8
2 4 3 6 3 2 5 5
Sample output:
4 6

Analysis:

Bitwise XOR or ^ has the following properties:

1. Either the number is different or it itself equals 0.

2. Different or satisfying identities (a^b) ^b=a, which can also be used for the fast exchange of variable values, although the subject does not need to be exchanged for variable values .

Therefore, the problem can be solved by using two-time XOR operation features:

(1) First from beginning to end in order to different or the original array of each number, then the final result is just one occurrence of the number of the same or the result, because the pairs appear two times the number is offset in the XOR.
(2) There are two digits in the original array only once, and two occurrences of the number must not be equal, their XOR result must not be 0, there must be a number in a bit (recorded as the last K-bit) there is 1, the other number of this bit does not have 1. So we think of a way to divide the original array into two sub-arrays, so that each sub-array contains a single occurrence of the number, a sub-array of this bit must have 1, and the other sub-array of this bit must not be 1, and then each sub-array is different or, because the divided two sub-arrays have such characteristics: the other number Only one number appears once. Therefore, we can use the bitwise XOR operation again to get the number that appears only once in two parts.


AC Code:

#include <iostream> #include <vector>using namespace Std;class solution {public:void findnumsappearonce (  vector<int> data,int* num1,int *num2)//The size order of the return value is not required, and the input array is not necessarily an ordered {if (data.size () <2) return;  The return value is type void, and the exit should write int partflag=0x1; Partflag is a dividing sign for two classes of numbers, which is a variable int xorres=0;for (int i=0; i<data.size (); i++) xorres ^= data[i];*num1 = xorres;*num2 = Xorres;  while ((Xorres & Partflag) ==0) Partflag <<= 1; A & 0x1 is equivalent to a%2, which is used to determine whether the last digit is 0 or 1,///To find a position in Xorres, the highest bit of Partflag (the countdown k bit) is 1, the other bit is full 0for (int i= 0; I<data.size (); i++) {if ((Data[i] & Partflag) ==0) *num1 ^= data[i];//Determine whether the count of the last K bits in the data array is 0 or 1,* NUM1 is the larger of the two single occurrences of the number of else *num2 ^=data[i];    *NUM1 is the larger of the two single occurrences of the number, *num2 is smaller}}};//the following is the test int main () {vector<int> data1 = {3,1,10,1,3,6,2,6};    int* NUM1 = new int;    int* num2 = new int;    Solution Sol; Sol.    Findnumsappearonce (Data1, NUM1, num2);    cout<<*num1<< "" <<*num2<<endl; return 0;}



This topic has a simplified version:


136. Single number

Submission URL: https://leetcode.com/problems/single-number/


< Span class= "Total-ac text-info" style= "line-height:20px; Color:rgb (49,112,143); font-size:13px; Vertical-align:text-bottom ">total accepted: 127018 &NBSP; total submissions: 255025 &NBSP; difficulty: medium

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?


AC Code:

#include <iostream> #include <vector>using namespace Std;class solution {public:    int Singlenumber ( vector<int>& nums)    {        if (nums.size () <1) return 0;          int res, xorres=0;        for (int i=0; i<nums.size (); i++)            xorres ^= nums[i];        res = xorres;           return res;    }}; int main () {    vector<int> data1 = {3,1,10,1,3,6,6};    Solution Sol;    int Res1=sol.singlenumber (DATA1);    cout<<res1<<endl;    return 0;}

RELATED Links: https://yq.aliyun.com/articles/3511


The sword points to the offer surface question 40: Two numbers in an array that appear only once

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.