2022.03.07 - NC035.BM52 数组中只出现一次的两个数字

1. 题目

在这里插入图片描述

2. 思路

(1) 位运算

  • 将所有数字进行异或运算,结果即为两个只出现一次的数字进行异或运算的结果。
  • 找出该结果中任意一位值为1的二进制位,根据该二进制位,可以将所有数字分为两组,两个只出现一次的数字必定各在一组,其他数字必定两两出现在某一组。
  • 分别对两组中所有数字进行异或运算,即可得到两个只出现一次的数字。

3. 代码

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param array int整型一维数组
     * @return int整型一维数组
     */
    public int[] FindNumsAppearOnce(int[] array) {
        int[] res = new int[2];
        int num = 0;
        int n = array.length;
        for (int i = 0; i < n; i++) {
            num ^= array[i];
        }
        int bit = 1;
        while (true) {
            if ((bit & num) != 0) {
                break;
            }
            bit <<= 1;
        }
        for (int i = 0; i < n; i++) {
            if ((array[i] & bit) == 0) {
                res[0] ^= array[i];
            } else {
                res[1] ^= array[i];
            }
        }
        if (res[0] > res[1]) {
            int temp = res[0];
            res[0] = res[1];
            res[1] = temp;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值