数组中只出现一次的两个数字

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

Python代码

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        xor_rlt = reduce(lambda x, y: x^y, array) # 全部按位异或
        if xor_rlt == 0:
            return
        index = 0
        while xor_rlt&1 == 0: # 找到异或结果的某一位不为0,则该位可以将数据分为两部分,其中每部分包含一个只出现一次的数字
            xor_rlt = xor_rlt >> 1
            index += 1
        result = [0, 0]
        for item in array:
            tmp = item >> index
            if tmp&1 == 1:
                result[0] ^= item
            else:
                result[1] ^= item
        return result

Java代码

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    public void FindNumsAppearOnce(int [] array, int num1[], int num2[]) {
        int xorRlt = 0;
        for(int x : array) {
            xorRlt ^= x;
        }
        int index = 0;
        while((xorRlt & 1) == 0) {
            xorRlt = xorRlt >> 1;
            index++;
        }
        for(int x : array) {
            if((x >> index & 1) == 0) {
                num1[0] ^= x;
            } else {
                num2[0] ^= x;
            }
        }
    }
}
posted @ 2017-08-29 21:35  HitAnyKey  阅读(186)  评论(0编辑  收藏  举报