1. 程式人生 > >使用python刷Leetcode演算法題(第一週)

使用python刷Leetcode演算法題(第一週)


明年六月份開始找工作,因此從這周開始刷題,希望記錄一下刷題的過程,由於種種原因選擇了python進行刷題,我會在每週的週日記錄下本週在Leetcode中刷過的題,並附上程式碼以及心得,以作備忘。。。。。

Two Sum

  • 第1題

英文描述:Given an array of integers, return indices of the two numbers such that they add up to a specific

target.You may assume that each input would have exactly one solution, and you may not use the same

element twice.

例子:

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

題目描述: 找到一個數組中兩個值得和等於固定值(target)返回這倆值得索引
解法:

def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i

解析: 利用一個字典,它的key是當前遍歷的值與target相差多少,value是當前值得索引。在遍歷陣列時候,每當遍歷到一個值時就檢視與target的差值在不在字典中,如果在就返回當前索引,不在就把[差值,索引]記錄。

Reverse Integer

  • 第2題

英文描述: Given a 32-bit signed integer, reverse digits of an integer.

note: Assume we are dealing with an environment which could only hold integers within the 

32-bit signed integer range. For the purpose of this problem, assume that your function

returns 0 when the reversed integer overflows.

例子:

Input: 123  Output:  321 
Input: -123   Output: -321
Input: 120  Output: 21

中文描述:返轉一個正數,如果溢位返回0
解法:

def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x<0:
            return -self.reverse(-x)
        new_num = 0
        while x:
            new_num = x%10 + new_num*10
            x = x//10
        if new_num>2147483647:
            return 0
        return new_num

解析:將所給的數字利用餘數法重構成新的正數

Palindrome Number

  • 第3題

英文描述:Determine whether an integer is a palindrome. Do this without extra space.

中文描述:不用額外空間判段一個數是不是迴文
解法:

def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        p = x
        q = 0
        while p >= 10:
            q *= 10
            q += p % 10
            p //= 10
        return q == int(x/10) and p == x%10

解析: 利用一個遍變數重構所給定的正數,重構方法就是獲取正數最後一位然後慢慢增加位數,最終返回的值與當前值得(除去最後一位是否相等)

Roman to Integer

  • 第4題

英文描述: Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from

1 to 3999.

中文描述: 將羅馬數字轉成中文,其中假設羅馬數字在1—3999中。

羅馬數字轉成整數描述:

羅馬數字共有七個,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。按照下面的規則可以表示任意正整數。
重複數次:一個羅馬數字重複幾次,就表示這個數的幾倍。 
右加左減:在一個較大的羅馬數字的右邊記上一個較小的羅馬數字,表示大數字加小數字。在一個較大的數字的左邊記上一個較小的羅馬數字,表示大數字減小數字。但是,左減不能跨越等級。比如,99不可以用IC表示,用XCIX表示。 
加線乘千:在一個羅馬數字的上方加上一條橫線或者在右下方寫M,表示將這個數字乘以1000,即是原數的1000倍。同理,如果上方有兩條橫線,即是原數的1000000倍。 
單位限制:同樣單位只能出現3次,如40不能表示為XXXX,而要表示為XL。

解法:

    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roman2int = {"I": 1,"V" :5,"X": 10, "L": 50, "C": 100,"D": 500,"M":1000}
        s_list = list(s)
        l_list = []
        for i in s_list:
            l_list.append(roman2int.get(i))
        res = 0
        for j in range(len(l_list) - 1):
            if l_list[j]<l_list[j+1]:
                res -=l_list[j]
            else:
                res +=l_list[j]
        res += l_list[-1]
        return res

解析: 整體思想就是把原來的羅馬字串轉成數字list,然後再根據羅馬轉整數規則轉換

Valid Parentheses

  • 第5題

英文描述:Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is

valid.The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

中文描述:判斷一個字串標點是否合法
解法:

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s_f = list(s)
        if len(s_f) % 2 != 0:
            return False
        else:
            judge = ["()","{}","[]"]
            stack = []
            for l in s_f:
                try:
                    stop = stack.pop()
                except:
                    stack.append(l)
                    continue
                if stop + l in judge:
                    continue
                else:
                    stack.append(stop)
                    stack.append(l)
            if len(stack) != 0:
                return False
            else:
                return True

解析: 利用了python中list可以實現棧的思想。

Merge Two Sorted Lists

  • 第6題

英文描述: Merge two sorted linked lists and return it as a new list. The new list should be made by

splicing together the nodes of the first two lists.
例子:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

中文描述:有序合併兩個listNode
解法:

def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

解析: 採用了遞迴的思想,從兩個listNode一個一個拿下來合併

Remove Duplicates from Sorted Array

  • 第7題

英文描述: Given a sorted array, remove the duplicates in-place such that each element appear only once

and return the new length.Do not allocate extra space for another array, you must do this by modifying

the input array in-place with O(1) extra memory.
例子:

Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

中文描述: 使用O(1)的空間複雜度去重
解法:

def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        length = 0
        for i in range(1,len(nums)):
            if nums[i] != nums[length]:
                length += 1
                nums[length] = nums[i]
        length += 1
        return length

解析: 利用兩個索引,一個從0開始(最終要返回的),一個從1開始,遍歷陣列

Remove Element

  • 第8題

英文描述:Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
例子:

Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.

中文描述:在陣列中刪除與給定值相等並且不改變原來的順序、使用O(1)的空間複雜度
解法:

def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        for i in range(nums.count(val)):
            nums.remove(val)
        return len(nums)

解析:採用python的內建函式list.count() 和list.remove()

Implement strStr()

  • 第9題

英文描述: Implement strStr().Return the index of the first occurrence of needle in haystack, or -1 if needle

is not part of haystack.
例子:

Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1

中文描述: 查詢字串中第一個出現目標字元的索引,沒有,返回-1
解法:

def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

解析: 採用python的內建函式str.find()

Search Insert Position

  • 第10題

英文描述:Given a sorted array and a target value, return the index if the target is found. If not, return the

index where it would be if it were inserted in order.You may assume no duplicates in the array.
例子:

Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0

中文描述:如果一個數在陣列中,返回索引,否則返回插入位置的索引
解法:

def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums_copy = nums[:]
        if target < nums_copy[0]:
            nums_copy.insert(0, target)
            return 0
        for i in range(len(nums) - 1):
            if nums[i] == target:
                return i
            if nums[i + 1] > target and nums[i] < target:
                l = i
                nums_copy.insert(l + 1, target)
                return l + 1
        if target == nums_copy[-1]:
            return len(nums_copy) - 1
        else:
            nums_copy.append(target)
        return len(nums_copy) - 1

解析:直接遍歷陣列,考慮小於陣列第一個,大於陣列最後一個,在陣列中,插入陣列中

Maximum Subarray

  • 第11題

英文描述: Find the contiguous subarray within an array (containing at least one number) which has the

largest sum.
例子:

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

中文描述: 查詢陣列中和最大的子陣列的和
解法:

def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0 
        curSum = maxSum = nums[0]
        for num in nums[1:]:
            curSum = max(num, curSum + num)
            maxSum = max(curSum, maxSum)
        return maxSum

解析: 採用兩個變數記錄陣列的當前和與最大和,從第一個值開始遍歷陣列

Length of Last Word

  • 第12題

英文描述: Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.
例子:

Input: "Hello World"
Output: 5

解法:

def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == "":
            return 0
        l = s.split(" ")
        for i in l[::-1]:
            if i == "":
                continue
            else:
                return len(i)
        return 0

解析: 直接逆序字串,遍歷字串,直到出現一個空字元

Plus One

  • 第13題

英文描述:Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

中文描述: 給一個非負整數加1,返回它的list

解法:

def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        num = 0
        for i in range(len(digits)):
            num += digits[i] * pow(10, (len(digits)-1-i))
        return [int(i) for i in str(num+1)]

解析: 先把整數list收整合一個整數,在拆分

Add Binary

  • 第14題

英文描述: Given two binary strings, return their sum (also a binary string).

例子:

For example,
a = "11"
b = "1"
Return "100".

中文描述: 將兩個二進位制字串相加,返回一個字串
解法:

def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if len(a)==0: return b
        if len(b)==0: return a
        if a[-1] == '1' and b[-1] == '1':
            return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
        if a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[0:-1],b[0:-1])+'0'
        else:
            return self.addBinary(a[0:-1],b[0:-1])+'1'

解析:採用遞迴的思想

Sqrt(x)

  • 第15題

英文描述: Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

例子:

Input: 4
Output: 2

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

解法:

def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        return math.floor(math.sqrt(x))

解析: 對x開方之後向下取整

Climbing Stairs

  • 第16題

英文描述: You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

例子:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

中文描述: 上樓,一次可以走1步或者2步,問到頂需要多少步
解法:

def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        if n == 2:
            return 2
        a = 1
        b = 2
        s = 0
        for i in range(n-2):
            s = a + b
            a = b
            b = s
        return s

解析:類比 Fibonacci sequence

Remove Duplicates from Sorted List

  • 第17題

英文描述:Given a sorted linked list, delete all duplicates such that each element appear only once.

例子:

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

中文描述: 對一個listNode去重
解法:

def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur:
            while cur.next and cur.next.val == cur.val:
                cur.next = cur.next.next
            cur = cur.next
        return head

解析:利用連結串列刪除節點

Merge Sorted Array

  • 第18題

英文描述:Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

The number of elements initialized in nums1 and nums2 are m and n respectively.

中文描述:將兩個有序數組合併成一個有序陣列
解法:

def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        while m > 0 and n > 0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[m+n-1] = nums1[m-1]
                m -= 1
            else:
                nums1[m+n-1] = nums2[n-1]
                n -= 1
        if n >0:
            nums1[:n] = nums2[:n]

解析: 將兩個陣列的最大的值依次移動到最長陣列(nums1)的最右側

Same Tree

  • 第19題

英文描述:Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

例子:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

中文描述:判斷兩個二叉樹是否相等
解法:

def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right,q.right)

解析:採用遞迴的思想

Symmetric Tree

  • 第20題

英文描述: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

例子:

 For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following [1,2,2,null,3,null,3] is not:
    1
   / \
  2   2
   \   \
   3    3

中文描述:檢查二叉樹是否映象對稱

解法:

def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isMirror(root, root1):
            if root == None and root1 == None:
                return True
            if root is None or root1 is None:
                return False
            return (root.val == root1.val) and isMirror(root.left, root1.right) and isMirror(root.right, root1.left)
        return isMirror(root,root)

解析:定義一個方法,判斷兩個兩顆二叉樹是否相等;然後判斷一顆是不是對稱就可以轉化為以當前結點的左右子樹是否相等

Maximum Depth of Binary Tree

  • 第21題

英文描述:Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the

farthest leaf node.

中文描述: 尋找一個二叉樹的最長路徑

解法:

def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        if root.left == None and root.right == None:
            return 1
        length = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
        return length

解析: 採用遞迴的思想進行求解

Binary Tree Level Order Traversal II

  • 第22題

英文描述: Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left

to right, level by level from leaf to root).
例子:

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]

中文描述:從上到下,從左到右返回二叉樹的節點
解法:

def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        stack = [(root,0)]
        res = []
        while stack:
            node, level = stack.pop()
            if node:
                if len(res) < level +1:
                    res.insert(0,[])
                res[-(level + 1)].append(node.val)
                stack.append((node.right, level + 1))
                stack.append((node.left, level + 1))
        return res

解析: 利用python的list實現的棧的結構求解,按照層次遍歷的方法

Convert Sorted Array to Binary Search Tree

  • 第23題

英文描述: Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two

subtrees of every node never differ by more than 1.

例子:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

中文描述: 將一個有序陣列轉成平衡二叉樹

解法:

def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None

        mid = math.floor(len(nums) / 2)

        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

解析: 採用遞迴的思想,一個有序陣列轉成二叉平衡樹,先獲取到中間的值,當作根,然後比它小的是左子樹,比它大的為右子樹,做迴圈

Balanced Binary Tree

  • 第24題

英文描述: Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two

subtrees of every node never differ by more than 1.

中文描述:判斷一個二叉樹是不是平衡二叉樹

解法:

def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def getDepth(root):
            if root == None:
                return 0
            if root.left == None and root.right == None:
                return 1
            l = getDepth(root.left)
            r = getDepth(root.right)
            if l == -99 or r == -99 or max(l,r) - min(l,r) > 1:
                return -99
            return max(l, r) + 1
        if root == None:
            return True 
        return getDepth(root) != -99

解析:利用平衡二叉樹的左子樹和右子樹的差的絕對值不大於1求解

Minimum Depth of Binary Tree

  • 第25題

英文描述:Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

中文描述:找出二叉樹中最短路徑

解法:

def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """ 
        if root == None:
            return 0
        l = self.minDepth(root.left)
        r = self.minDepth(root.right)
        if l == 0 or r == 0:
            return l +r + 1
        else:
            return min(l,r) + 1

解析: 利用遞迴思想求解,主要特殊考慮單枝樹

Path Sum

  • 第26題

英文描述: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up

all the values along the path equals the given sum.

例子:

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

中文描述:判斷二叉樹中是否有路徑的和等於給定的值

解法:

def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        if not root.left and not root.right and root.val == sum:
            return True
        sum -= root.val
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

解析: 利用先序遍歷的遞迴思想,每次遍歷一個值都減去當前值

不要嫌棄一週刷的慢,實在是事多,我一般只有晚上才會刷題,等開題之後閒下來了就主刷題啦,希望最後能找到一個適合自己的工作,哈哈哈