Single Number

本文介绍三种算法,用于在数组中找到仅出现一次的元素。SingleNumber使用异或解决两次重复问题;SingleNumberII介绍如何在线性时间和常数空间复杂度内找出三次重复中的独特值;SingleNumberIII提供了解决两个唯一元素的方案。

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

Single Number

Given an 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?


这个题用位操作中的亦或:

a^a=0,a^0=a,a^b^b=a

public class Solution {
    public int singleNumber(int[] nums) {
    	int res = nums[0];
        for (int i = 1; i < nums.length; ++i) res ^= nums[i];
        return res;
    }
}

Single Number II

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

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

建立一个32位的数字,来统计每一位上1出现的个数,我们知道如果某一位上为1的话,那么如果该整数出现了三次,对3去余为0,我们把每个数的对应位都加起来对3取余,最终剩下来的那个数就是单独的数字。

public int singleNumber(int[] nums) {
    int res = 0;
    for (int i = 0; i < 32; ++i) {
        int sum = 0;
        for (int j = 0; j < nums.length; ++j) {
            sum += (nums[j] >> i) & 1;
        }
        res |= (sum % 3) << i;
    }
    return res;
}

Single Number III

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?

首先计算nums数组中所有数字的异或,记为xor
令lowbit = xor & -xor,lowbit的含义为xor从低位向高位,第一个非0位所对应的数字
例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码,two's complement)
则lowbit = 2(二进制:0010)
根据异或运算的性质,“同0异1”
记只出现一次的两个数字分别为a与b
可知a & lowbit与b & lowbit的结果一定不同
通过这种方式,即可将a与b拆分开来

public class Solution {
    public int[] singleNumber(int[] nums) {  
        int[] res = new int[2];  
        int result = nums[0];  
        for(int i=1;i<nums.length;i++){  
            result = result^nums[i];  
        }  
        res[0] = 0;  
        res[1] = 0;  
        int n = result & (~(result-1));  
        for(int i=0;i<nums.length;i++){  
            if((n & nums[i])!=0){  
                res[0] = res[0] ^ nums[i];  
            }else {  
                res[1] = res[1] ^ nums[i];  
            }  
        }  
        return res;  
    }  
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值