小旭讲解 LeetCode 260. Single Number III
小旭讲解 LeetCode 260. Single Number III

BiliBili

YouTube

原题

中文

给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

English

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?

分析

小旭讲解 LeetCode 260. Single Number III4
小旭讲解 LeetCode 260. Single Number III
小旭讲解 LeetCode 260. Single Number III
小旭讲解 LeetCode 260. Single Number III

代码

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> ans{0, 0};
        int i = 0;
        for (auto& n : nums) {
            i ^= n;
        }
        i &= (-i);
        for (auto& n : nums) {
            if ((i & n) == 0) {
                ans[0] ^= n;
            } else {
                ans[1] ^= n;
            }
        }
        return ans;
    }
};

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

参考

原题链接:https://leetcode.com/problems/single-number-iii/

欢迎分享,引用。若转载,请联系我,谢谢配合。
本文地址:https://qoogle.top/xiaoxu-explaination-leetcode-260-single-number-iii/
0 0 vote
Article Rating
Subscribe
提醒
guest
1 评论
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

[…] 阅读原文 […]