1. 程式人生 > >【一】Leetcode之Python刷題之路

【一】Leetcode之Python刷題之路

  申請完了github帳號,又在Leetcode上發現了新大陸,從昨天開始刷題了,感覺很有意思。看視訊學習Python動手不太多,現在開始刷題練習自己的程式碼水平,leetcode上還有很多大神,快哉美哉!
  程式碼我都放到github裡了https://github.com/Ray1225/Python_Training,歡迎大家關注並指正。話不多說,怒上程式碼。

1. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.
Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

簡單點說,就是輸入兩個數字,比較兩個數字的二進位制的差異,最終輸出差異的距離——hamming距離。

  首先說一下我的思路,我在IDLE試了一下1轉化成2進製為’0b1’,4轉化為二進位制為’0b100’,如果用string的方式來逐一比較的話需要將1的二進位制’0b1’補齊,和’0b100’保持一致即’0b001’,這樣才可以逐一對比,並計算”hamming distance”。

class Solution(object):
    def hammingDistance(self,x, y):
        c = bin(x)
        d = bin(y)
        (c1,c2)=c.split('b') #將二進位制分割,我們僅需要'0b'右邊的有效數字
        (d1,d2)=d.split('b')
        #通過下述程式碼來達到兩個二進位制數能夠相互對齊的目的。
        if len(c2)>len(d2):
            d3 = d2.zfill(len(c2))# 這裡zfill()函式是返回,並不是將d2修改,這裡不要犯錯。
c3 = c2 else: c3 = c2.zfill(len(d2)) d3 = d2 countall = 0 number = 0 for i in c3:# 進行計算hamming distance if i != d3[number]: countall+=1 number+=1 return countall

上面的程式碼最後提交成功了,但是自己感覺程式碼太辣雞,看了Disscusion裡大神的程式碼,真的折服了,一行搞定。

return bin(x^y).count('1') # python裡'^'符號為求異或

2. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.
即給定一個均為整數的陣列,除了其中一個數字出現一次,其他均出現了兩次,找到這個出現一次的數字。加入給[1,2,3,3,4,4,2],則輸出1。

  首先將該陣列從小到達排序,然後依次從第二個數開始,對比其是否與第1個不同且與第3個不同,如果是,則代表該數字為我們要找的。程式碼如下:

class Solution(object):
    def singleNumber(self, nums):
        if len(nums) == 1:#如果陣列長度為1,則輸出該數字。其實我這裡考慮多了,題目的意思應該是該陣列長度大於等於3
            return nums[0]
        else:
            nums.sort()# 排序
            #以下兩個if判斷頭尾兩個數字是否為single number
            if (nums[0] != nums[1]):
                return nums[0]
            if (nums[len(nums)-1] != nums[len(nums)-2]):
                return nums[len(nums)-1]
            else:
                for i in range(1,len(nums)-1):
                    if (nums[i]!=nums[i+1] and nums[i]!=nums[i-1]):
                        return nums[i]

下面上一下大神的程式碼:
Approach 1: 這是一個比較討巧的方法,直接將原陣列用set()去重以後,求和並乘2再減去原陣列的和,得到single number。厲害

class Solution(object):
    def singleNumber(self, nums):
        return 2 * sum(set(nums)) - sum(nums)

Approach 2:利用Hash表來實現,這裡將數組裡的數賦值為雜湊表的下標,也很巧妙,且複雜度低。

class Solution(object):
    def singleNumber(self, nums):
        Hash_table = {}
        for i in nums:
            try:
                Hash_table.pop(i) #如果該下標存在資料,則刪除.如果某數字出現兩次,則會被新增一次和刪除一次
            except:# 否則,將該下標的資料賦值為1
                Hash_table[i] = 1
        return Hash_table.popitem()[0]

3. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
給定一陣列,共n個數,求這個陣列中[1,n]內未出現的數字。
Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

我的程式碼:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        length = len(nums) # 求陣列長度
        nums.sort() # 排序陣列
        num_set = set(nums) # 去重
        list_allset = set(list(range(1,length+1))) #定義一個從1到n開始的set
        return list(list_allset - num_set) #兩個set相減便得到最終結果

這個問題對自己的程式碼還是比較滿意的,以上問題大家有好的想法思路或者覺得我寫的有問題,歡迎留言交流,謝謝!