1. 程式人生 > >LeetCode 總結(第1 7 9 13 14題)

LeetCode 總結(第1 7 9 13 14題)

1 兩數之和

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        
        """
        #方法一:
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                p_target = nums[i] + nums[j]
                if p_target == target:
                    return [i,j]
        """
        #方法二:
        hashed = {}
        for i in range(len(nums)):
        	if target - nums[i] in hashed:
        		return [hashed[target-nums[i]],i]
       		hashed[nums[i]] = i

7 反轉整數

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        if (-2**31 <= x <= (2**31-1)):
            a = 0
            if x > 0:
                x_str = str(x)
                for i in range(len(x_str)-1):
                    if x_str[-(i+1)] == 0:
                        a = i
                        break
                x_reverse = int(x_str[-(a+1):-(len(x_str)+1):-1])
                if (-2**31 <= x_reverse <= (2**31-1)):
                    return x_reverse
                else:
                    return 0
            if x == 0:
                return x

            if x < 0:
                x_str = str(abs(x))
                for i in range(len(x_str)-1):
                    if x_str[-(i+1)] == 0:
                        a = i
                        break
                x_reverse = -int(x_str[-(a+1):-(len(x_str)+1):-1])
                if (-2**31 <= x_reverse <= (2**31-1)):
                    return x_reverse
                else:
                    return 0
        else:
            return 0

9 迴文數
方法一:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        
        if x < 0:
            return False
        
        if x >= 0:
            x_str = str(x)
            x_reverse = int(x_str[-1:-(len(x_str)+1):-1])
            if x_reverse == x:
                return True
            else:
                return False

方法二:
不將整數轉化成字串,因為這將又要花費額外的空間。我們考慮只反轉數字的一半

if x < 0 or (x % 10 == 0 and x != 0): 
	return False 
y = 0 
while(x > y): 
	y = y * 10 + x % 10 
	x //= 10 
return x==y or x == y//10

13 羅馬數字轉整數

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        #定義一個字典
        dictionary = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000, "IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900}
        double_word = ["IV", "IX", "XL", "XC", "CD", "CM"]
        output = 0
        i = 0

        while(i < len(s)):
            if s[i:i+2] in double_word:
                output = output + dictionary[s[i:i+2]]
                i += 2
                print(output)
            else:
                output = output + dictionary[s[i]]
                i += 1 
                print(output)
        return output

14 最長公共字首
我的程式碼:

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        import numpy as np
        
        flag = 1
        
        if len(strs) == 0:
            return ""
        
        #首先獲得序列的最短長度
        min_len = np.inf #這是numpy裡面的函式
        for i in range(len(strs)):
            if len(strs[i]) < min_len:
                min_len = len(strs[i])
                min_i = i
                
        if min_len ==  0:
            return ""
                
        for j in range(min_len):
            for i in range(len(strs)):
                if strs[i][j] != strs[min_i][j]:
                    best_j = j
                    flag = 0
                    break
            if flag == 0:
                break
            if (j == (min_len - 1) and flag == 1):
                best_j = min_len
        return strs[min_i][:best_j]           

大神的:

def longestCommonPrefix(strs):
    """
    :type strs: List[str]
    :rtype: str
    """

    res = "" 
    if len(strs) == 0: 
        return ""
    
    for each in zip(*strs):#zip()函式用於將可迭代物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的列表 
        if len(set(each)) == 1:#利用集合建立一個無序不重複元素集 
            res += each[0]
        else:
            break
    return res