剑指offer (40)

题目 : 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路 :
首先,位运算中异或的性质:两个相同数字异或=0,一个数和0异或还是它本身。
当只有一个数出现一次时,我们把数组中所有的数,依次异或运算,最后剩下的就是落单的数,因为成对儿出现的都抵消了。
依照这个思路,我们来看两个数(我们假设是AB)出现一次的数组。我们首先还是先异或,剩下的数字肯定是A、B异或的结果,这个结果的二进制中的1,表现的是A和B的不同的位。我们就取第一个1所在的位数,假设是第3位,接着把原数组分成两组,分组标准是第3位是否为1。如此,相同的数肯定在一个组,因为相同数字所有位都相同,而不同的数,肯定不在一组。然后把这两个组按照最开始的思路,依次异或,剩余的两个结果就是这两个只出现一次的数字。

1、java版本

	// 找到两个数组 分别储存着两个只出现一次的值
	public static void findNumsAppearOnce(int[] array, int[] num1, int[] num2) {
		int length = array.length;
		if (length == 2) {
			num1[0] = array[0];
			num1[1] = array[1];
			return;
		}
		int bitResult = 0;
		for (int i = 0; i < length; i++) {
			bitResult ^= array[i];
		}
		int index = findFirst1(bitResult);
		for (int i = 0; i < length; i++) {
			if (isBit1(array[i], index)) {
				num1[0] ^= array[i];
			} else {
				num2[0] ^= array[i];
			}
		}

	}

	// 从右向左找到第一个为1的位
	public static int findFirst1(int bitResult) {
		int index = 0;
		while (((bitResult & 1) == 0) && index < 32) {
			bitResult >>= 1;
			index++;
		}
		return index;
	}

	// 判断一个数的某一位是否为1
	public static boolean isBit1(int target, int index) {
		return ((target >> index) & 1) == 1;
	}

2、C++版本

//
// Created by stephen on 2021/3/11.
//
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param array int整型vector
     * @return int整型vector
     */
    vector<int> FindNumsAppearOnce(vector<int>& array) {
        // write code here
        set<int> s;
        for (int  num:array){
            if (s.count(num))
                s.erase(num);
            else
                s.insert(num);
        }
        vector<int> res;
        for (auto iter = s.begin(); iter != s.end(); iter++)
            res.push_back(*iter);
        sort(res.begin(),res.end());
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值