[LeetCode 解题报告]260. Single Number III

蓝咒 提交于 2020-02-11 06:37:11

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:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        if (nums.empty())
            return {};
        
        int diff = 0;
        for (int i = 0; i < nums.size(); i ++)
            diff ^= nums[i];
        
        diff &= -diff;
        vector<int> res(2, 0);
        for (int i = 0; i < nums.size(); i ++) {
            if (nums[i] & diff)
                res[0] ^= nums[i];
            else
                res[1] ^= nums[i];
        }
        return res;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!