LeetCode笔记:137. Single Number II

本文介绍了一种在整数数组中寻找唯一出现一次的整数的算法,该算法具备线性时间复杂度且不使用额外内存,通过巧妙地运用位运算实现了这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

大意:

给出整数数组,每个元素都出现三次,只有一个元素只出现一次,找到它。

注意:
你的算法应该是线性时间复杂度。能不用额外的空间来做吗?

思路:

用哈希表也可以做到线性时间复杂度,但是用了额外空间。

这里我们参考这个思路来做:传送门:算法题总结之找到数组中出现次数唯一不同的数字

代码(Java):

public class Solution {
    public int singleNumber(int[] nums) {
        int x1 = 0;
        int x2 = 0;
        int mask = 0;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            x2 ^= x1 & num;
            x1 ^= num;
            mask = ~(x1 & x2);
            x2 = x2 & mask;
            x1 = x1 & mask;
        }
        return x1;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.youkuaiyun.com/cloudox_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值