Skip to content

260. Single Number III

难度:Medium

刷题内容

原题连接

  • https://leetcode.com/problems/single-number-iii/

内容描述

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Example:

Input:  [1,2,1,3,2,5]
Output: [3,5]
Note:

The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

˼·1 **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***

������֮ǰ内容描述�в�ͬ内容描述��� single number����֮ǰ��˼άȥ���Ļ����ڶ内容描述内容描述���֮��õ���Ӧ内容描述 single number ���ֵaXorb内容描述��aXorbת���ɶ����ƣ��ӵ�0λ���𣬵�һ��Ϊ1��λ����˵�������λ��a �� b����ȣ内容描述е����ֳ������֣内容描述λ��Ϊ0��һ���֣�Ϊ1��һ���֣������Ͱ内容描述ֵ��˲�ͬ内容描述�С����ŷֱ内容描述�������ܵõ����

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int aXorB = 0;
        for (int num : nums) {
            aXorB ^= num;
        }
        int differingBit = 1;
        while ((differingBit & aXorB) == 0) {
            differingBit <<= 1;
        }
        int a = 0;
        int b = 0;
        for (int num : nums) {
            if ((num & differingBit) == 0) {
                a ^= num;
            } else {
                b ^= num;
            }
        }
        return {a, b};
    }
};


回到顶部