Leetcode 算法題01


現在沒有數據結構的知識直接轉機器學習去面試真的太難了,很多這種機器學習的崗位無論筆試面試都有很多數據結構的知識,有空也要做做數據結構的知識梳理。

從今天開始做Leetcode的算法題,以難度排序,由易到難,簡單的時候一天多做一些,一週休息一天,使用python語言,期間看裘宗燕的《數據結構與算法 Python語言描述》,主要目的是能熟練使用python並熟悉基本的數據結構,爲面試做準備。


461. Hamming Distance

兩個整數轉化爲二進制後,按位不同的個數,輸入0<x,y<2^31

Example:

Input: x = 1, y = 4

Output: 2

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

The above arrows point to positions where the corresponding bits are different.

我的代碼:

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        d = '00000000000000000000000000000000'
        a=bin(x)[2:]
        b=bin(y)[2:]
        xbin = d[:-len(a)]+a
        ybin = d[:-len(b)]+b
        distance = 0
        for i in range(32):
            if xbin[i] != ybin[i]:
                distance += 1
        return distance
大神的代碼:

class Solution(object):
    def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
	return bin(x^y).count('1')



657. Judge Route Circle

初始有一個機器人在座標(0,0)的位置,給出一個移動順序的序列,如果機器人回到原點則輸出True,移動指令分別爲:'R','L','U','D'

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false
我的代碼:

本來想初始化一個座標並進行移動計算,後來想到上面第一題大神的回答,稍微想了一下。

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        return moves.count('R') == moves.count('L') and  moves.count('U') == moves.count('D')



617. Merge Two Binary Trees

樹的合併

Example 1:

Input: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7
這道題因爲完全沒接觸過樹的知識,想了很久也沒做出來,基礎實在太差了,就看了一下討論,做了出來,要理解遞歸與self的意義

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if t1 == None and t2 == None:
            return None
        elif t1 == None:
            return t2
        elif t2 == None:
            return t1
        else:
            root = TreeNode(t1.val+t2.val)
            root.left = self.mergeTrees(t1.left,t2.left)
            root.right = self.mergeTrees(t1.right,t2.right)
        return root

561. Array Partition I

給出一個列表,兩兩分組爲(a1,b1),(a2,b2)...使min(ai,bi)的和儘可能大

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
我的代碼:總之就是將列表排序後隔一個取一個數累加

class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        ans = 0
        for i in range(len(nums)//2):
            ans += nums[i*2]
        return ans
大神的代碼:切片的使用

class Solution(object):

    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(sorted(nums)[::2])

476. Number Complement
給一個數,轉爲二進制後按位取反,輸出結果的十進制

我的代碼:replace那裏忘記賦值了,以爲和sort()函數一樣用了就自動賦值了

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        string = str(bin(num))[2:]
        string = string.replace('0','a')
        string = string.replace('1','0')
        string = string.replace('a','1')
        return int(string,2)
大神的代碼:用N個1按位異或

class Solution(object):
    def findComplement(self, num):
        i = 1
        while i <= num:
            i = i << 1
        return (i - 1) ^ num


500. Keyboard Row

給含多個單詞的列表,排除其中所有字母不在鍵盤一行內的單詞

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
我的代碼:
class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        line=['QWERTYUIOP','ASDFGHJKL','ZXCVBNM']
        ans = list(words)
        for word in words:
            flag = (word[0].upper() in line[0])+2*(word[0].upper() in line[1])
            +3*(word[0].upper() in line[2])
            for i in word.upper():
                if i not in line[flag-1]:
                    ans.pop(ans.index(word))
                    break
        return ans 
大神的代碼:使用了正則表達式

def findWords(self, words):
    return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)  #(?i) 表示所在位置右側的表達式開啓忽略大小寫模式


557. Reverse Words in a String III

輸入一個句子,將句子中每個單詞的字幕順序置反並輸出

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
我的代碼:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        wordlist=s.split()
        anslist=[]
        ans=""
        for word in wordlist:
            anslist.append(word[::-1])
        for i in anslist:
            ans += ' '
            ans += i
        return ans[1:]
大神的代碼:熟悉join函數,join函數只能用於字符串格式
def reverseWords(self, s):
    return ' '.join(s.split()[::-1])[::-1]




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章