zoukankan      html  css  js  c++  java
  • 数组中只出现一次的两个数字

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

    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;
                }
            }
        }
    }
    
  • 相关阅读:
    数据分析 ---上篇
    爬虫 ---模拟登录
    Spider -- 获取图片并处理中文乱码
    爬虫篇 ---增量式爬虫
    Django中间件深入理解
    认识casbin
    关于nginx开机自己启动配置
    更改redhat yum源
    sqlalchemy监听事件
    Linux命令 history
  • 原文地址:https://www.cnblogs.com/renzongxian/p/7450411.html
Copyright © 2011-2022 走看看