Prove safety Offer - 56 interview questions - I. times the number that appears in the array (or exclusive, packets)

1. Topic

An integer array nums in addition to the two figures, other figures appear twice. Please write a program to find these two figures appear only.

Required time complexity is O (n), the spatial complexity is O (. 1) .

示例 1:
输入:nums = [4,1,4,6]
输出:[1,6][6,1]

示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10][10,2]
 
限制:
2 <= nums <= 10000

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Similar topics:

136. LeetCode appears only once digital (exclusive OR ^)
LeetCode 137. Digital only appears once II (bit operation)

2. Problem Solving

  • For all values ​​of the array of all the exclusive OR, exclusive-OR value of two numbers to obtain the wanted requirements
  • Found value of the exclusive OR 1bit
  • With the bitvalue of the array to be divided into two groups, respectively, obtaining exclusive OR values, i.e., unique numbers from 2
class Solution {
public:
    vector<int> singleNumbers(vector<int>& nums) {
    	int i, XOR = 0;
    	for(i = 0; i < nums.size(); ++i)
    		XOR ^= nums[i];

    	for(i = 0; i < 32; ++i)
    	{
    		if(XOR & (1<<i))
    			break;
    	}
    	int a = 0, b = 0;
    	for(auto& n : nums)
    	{
    		if(n&(1<<i))
    			a ^= n;
    		else
    			b ^= n;
    	}
    	return {a, b};
    }
};

Here Insert Picture Description

Published 718 original articles · won praise 723 · views 220 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104827266