关闭

70 leetcode - Single Number I,II,III

标签: leetcodeSingleNumberPython算法
78人阅读 评论(0) 收藏 举报
分类:

Single Number I

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
'''
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]

        return reduce(lambda x,y:x^y,nums)

Single Number II

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
实现的思路是基于数组的元素是整数,统计整数的每一位来得到出现次数。
我们知道如果每个元素重复出现三次,那么每一位出现1的次数也会是3的倍数,
如果我们统计完对每一位进行取余3,那么结果中就只剩下那个出现一次的元素。
总体只需要对数组进行一次线性扫描,统计完之后每一位进行取余3并且将位数字赋给结果整数,
这是一个常量操作(因为整数的位数是固定32位),所以时间复杂度是O(n)。而空间复杂度需要一个32个元素的数组,也是固定的,因而空间复杂度是O(1)
'''
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length == 0:
            return 0

        bit_sum = [0] * 32
        for val in nums:
            for index in range(32):
                bit_sum[index] += (val >> index) & 1

        ret = 0
        #print bit_sum
        for index,val in enumerate(bit_sum[:-1]):
            ret += (val%3)<<index
        if bit_sum[-1]%3 == 1:
            return -(pow(2,31) - ret)
        return ret

if __name__ == "__main__":
    s = Solution()
    print s.singleNumber([1,3,3,3])
    print s.singleNumber([1])
    print s.singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2])
    print s.singleNumber([-401451,-177656,-2147483646,-473874,-814645,-2147483646,-852036,-457533,-401451,-473874,-401451,-216555,-917279,-457533,-852036,-457533,-177656,-2147483646,-177656,-917279,-473874,-852036,-917279,-216555,-814645,2147483645,-2147483648,2147483645,-814645,2147483645,-216555])

Single Number III

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
'''
class Solution(object):
    def __single(self,nums):
        ret = nums[0]
        for i in nums[1:]:
            ret = ret ^ i

        return ret

    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        length = len(nums)
        if length <= 2:
            return nums

        #两个只出现一次的数异或
        tmp = self.__single(nums)     

        diff_index = 0
        #寻找能区分两个数的那一位,因为tmp做的是异或
        while diff_index < 32:        
            if (tmp >> diff_index) & 1:
                break

            diff_index += 1

        #转换成了一个数组中有一个数出现一次,其余出现两次
        ret1 = ret2 = 0
        for i in nums:
            if (i>>diff_index) & 1:
                ret1 = ret1 ^ i
            else:
                ret2 = ret2 ^ i

        return [ret1,ret2]

if __name__ == "__main__":
    s = Solution()
    print s.singleNumber([1,2,3,3,4,4,2,5,5,10])
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    博客专栏
    个人资料
    • 访问:47715次
    • 积分:2201
    • 等级:
    • 排名:第18217名
    • 原创:177篇
    • 转载:12篇
    • 译文:0篇
    • 评论:2条