[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.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [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?

思路

题意:给定一个数组,其中除了两个数出现一次外,其他都出现两次,要求在时间复杂度为O(n)空间复杂度为O(1)的条件下找出这两个数。

题解:按照异或的思想,最后可以得到这两个出现一次的数的异或值,那么我们只需对这个异或值lowbit操作,得到其最低位为1的位在哪,然后根据lowbit后得到的值,将数据分为两堆,那么可以知道的是这两个出现一次的数肯定分布在不同的两堆中(因为是对这这两个数的异或值lowbit操作,因此其为1的最低二进制位,这两个数肯定一个数0一个是1),那么问题转化为子问题,有一堆数,出了一个数出现一次外,其他数都出现两次。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    //26ms
    vector<int> singleNumber(vector<int>& nums) {
        int diff = 0,one = 0,two = 0;
        vector<int>res;
        for (unsigned int i = 0;i < nums.size();i++){
            diff ^= nums[i];
        }
        diff &= (-diff);  //lowbit操作
        for (unsigned int i = 0;i < nums.size();i++){
            if (nums[i] & diff) one ^= nums[i];
            else    two ^= nums[i];
        }
        res.push_back(one);
        res.push_back(two);
        return res;
    }
};

  

 
posted @   zxzhang  阅读(248)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2016-08-19 树状数组求第k小的元素
点击右上角即可分享
微信分享提示

目录导航