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


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

    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;
                }
            }
        }
    }
    
  • 相关阅读:
    特效导航栏
    json基础用法
    CSS盒模型以及如何解决边距重叠问题
    JS设置和获取盒模型的宽和高
    太极图
    JS旋转和css旋转
    正则表达式三-元字符
    正则表达式语法二-量词
    逻辑运算符
    字符串和正则的相关方法
  • 原文地址:https://www.cnblogs.com/renzongxian/p/7450411.html
Copyright © 2020-2023  润新知