[LeetCode]Single Number

重新开始刷题,最近工作中都用python,就改用python写吧,从些简单的开始~LOL

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


1st Solution:

Running Time: O(n), 

Extra Space: O(n)

create a dictionary to record each number's frequency of occurrence.

class Solution():
    def singleNumber(self, A):
        dict = {}
        for item in A:
            if item in dict.keys():
                dict[item] += 1
            else:
                dict[item] = 1
        for n in dict.keys():
            if dict[n] == 1:
                return n
由于创建了额外的空间(dict), 1st solution 无法通过OJ.


2nd Solution:

Running Time: O(n)

Extra Space: none

Use XOR(Exclusive OR)

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        return reduce(lambda x,y:x^y, A)
区区一行代码,不得不感慨python的简洁精炼。


Reference:

(XOR): x ^ y, which does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.

Python lambda functions





你可能感兴趣的:(LeetCode,python)