Skip to content

[剑指 Offer] 56 - I. 数组中数字出现的次数 #82

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Aug 17, 2021 · 0 comments
Open

[剑指 Offer] 56 - I. 数组中数字出现的次数 #82

frdmu opened this issue Aug 17, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 17, 2021

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是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.length <= 10000

解法:
位运算,以前还真没这么做过。代码如下:

class Solution {
public:
    vector<int> singleNumbers(vector<int>& nums) {
        vector<int> res(2, 0);
        
        int x = 0; 
        for (auto n: nums) {
            x ^= n;
        }
        int g = x & (-x);
        for (auto n: nums) {
            if ((n & g) == 0) {
                res[0] ^= n;
            } else {
                res[1] ^= n;
            }
        }

        return res;
    }
};

Refer:
260. 只出现一次的数字 III

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant