python 整型数组

来源:互联网 发布:湖北旅游 知乎 编辑:程序博客网 时间:2024/06/02 05:30
牛客网上的剑指 offer的在线编程:

题目描述:

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

方法一:

# -*- coding: utf-8 -*-class Solution:    def yihuo(self, array):        result = 0        if len(array) == 1:            return array[0]        else:            for i in range(len(array) - 1):                if i == 0:                    result = array[i] ^ array[i + 1]                else:                    result = result ^ array[i + 1]        return result    def splitArray(self, array):        first = []        second = []        result = self.yihuo(array)        for j in range(len(bin(result))):            if bin(result)[j] == str(1):                for k in range(len(array)):                    if bin(array[k])[j - 4] == str(1):                        first.append(array[k])                    else:                        second.append(array[k])        return first, second    def FindNumsAppearOnce(self, array):        all = []        #result = self.yihuo(array)        first, second = self.splitArray(array)        result_first = self.yihuo(first)        result_second = self.yihuo(second)        all.append(result_first)        all.append(result_second)        return all

方法二:

# -*- coding:utf-8 -*-class Solution:    # 返回[a,b] 其中ab是出现一次的两个数字    def FindNumsAppearOnce(self, array):        # write code here        array.sort()        result = []        for i in range(len(array)):            if i == len(array) - 1:                if array[i] != array[i - 1]:                    result.append(array[i])            elif i == 0:                if array[i] != array[i + 1]:                    result.append(array[i])            elif (array[i] != array[i + 1]) and (array[i] != array[i - 1]):                result.append(array[i])        return result




0 0