【LeetCode】136. Single Number

本文详细介绍了LeetCode题目136.SingleNumber的解题思路,包括常规的两层循环解法和基于比特操作的高效解法。通过对比特位操作的深入理解,实现了一种线性时间复杂度且不需要额外内存的解决方案。

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

问题

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

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

Example 1:

Input: [2,2,1]
Output: 1
Example 2:

Input: [4,1,2,1,2]
Output: 4

思路

常规解法

两层循环,时间复杂度为o(n2)
空间复杂度为 o(n)

public int findSingle_1(int[] nums) {
        if (nums.length < 2) {
            return nums[0];
        }
        Set<Integer> hashSet = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            boolean isSingle = true;
            if(hashSet.contains(nums[i])) {
                continue;
            }
            hashSet.add(nums[i]);
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    isSingle = false;
                    break;
                }
            }
            if (isSingle) {
                return nums[i];
            }
        }
        throw new IllegalArgumentException("not found");
    }

基于比特操作的解法

原理:相同值的异或结果为0
时间复杂度 o(n),空间复杂度o(1)

public int findSingle_2(int[] nums) {
        int res = 0;
        for(int num : nums) {
            res ^= num;
        }
        return res;
    }

知识点

比特位操作

逻辑操作
a & b 与操作,有一个为0,则为0,否则为1
a | b 或操作,有一个为1,则为1,否则为0
a ^ b 异或操作,相同则为1,否则为0;若2个数相同,则异或操作后得到0;0 ^ a = a 任何值异或,得到自身;两个不相等的值异或,不可能得到0;
~ b 取反操作;

移位操作
<< 左移 等价于x2
‘>>’ 右移 等价于 /2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值