其他分享
首页 > 其他分享> > [leetcode] 260. Single Number III

[leetcode] 260. Single Number III

作者:互联网

Description

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) {
        int diff=0;
        for(int i=0;i<nums.size();i++){
            diff=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;
    }
};

参考文献

[LeetCode] Single Number III 单独的数字之三

标签:两个,数字,only,Single,260,数组,III,异或,appear
来源: https://blog.csdn.net/w5688414/article/details/95895203