• 数字出现的次数


    题目描述

    一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
    思路
    相同异或为0,相异异或为0,有两个出现一次,其他出现两次,想办法将这两个只出现一次的两个数分到不同的数组中。因为两个只出现1个,所以总体异或必不为0,从右往左,找第一个1的索引。根据这个索引把这个索引上是1的归为一组,其他的归为一组。
    代码实现
     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def FindNumsAppearOnce(self, array):
     4         # write code here
     5         if not array or len(array) < 2:
     6             return 0
     7         temp = 0
     8         res1 = 0
     9         res2 = 0
    10         for i in array:
    11             temp = temp ^ i
    12         # temp中1在的索引
    13         indexof1 = self.findIndex1(temp)
    14         for j in array:
    15             if self.is1(j,indexof1):
    16                 res1=res1^j
    17             else:
    18                 res2 = res2^j
    19         return res1,res2
    20 
    21     def findIndex1(self,num):
    22       23         n = 0
    24         while num &1==0:
    25             num = num>>1
    26             n +=1
    27         return n
    28     def is1(self,num,index1):
    29         if (num>>index1)&1:
    30             return True
    31         else:
    32             return False
  • 相关阅读:
    1-5-03:均值
    1-5-01:求平均年龄
    1-04-t6993:二进制位处理
    1-4-20:求一元二次方程的根
    1-4-19:简单计算器
    1-4-18:点和正方形的关系
    1-4-17:判断闰年
    1-4-16:三角形判断
    1-4-15:最大数输出
    停止IIS服务
  • 原文地址:https://www.cnblogs.com/shuangcao/p/12773612.html
Copyright © 2020-2023  润新知