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

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

第二週了。。。又刷了一週,這周明顯感覺刷起來更順了,加油!!!!

Pascal’s Triangle

英文描述: Given numRows, generate the first numRows of Pascal’s triangle.
例子:

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

中文描述:給定特定的行,返回一個楊輝三角的列
解法:

def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
triangle = [] for row_num in range(numRows): row = [None for _ in range(row_num+1)] row[0], row[-1] = 1, 1 for j in range(1, len(row)-1): row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j] triangle.append(row) return
triangle

解析:利用楊輝三角的性質,當前行至於前面一行的值有關

Pascal’s Triangle II

英文描述:Given an index k, return the kth row of the Pascal’s triangle.
例子:

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

中文描述: 返回楊輝三角的第k行元素,算是楊輝三角的進階
解法:

def getRow
(self, rowIndex):
""" :type rowIndex: int :rtype: List[int] """ row = [1] for _ in range(rowIndex): row = [x + y for x, y in zip([0] + row, row+[0])] return row

解析: 僅僅利用一個列表儲存當前行的值就行了

Best Time to Buy and Sell Stock

英文描述: Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
例子:

Example 1:
    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
    Input: [7, 6, 4, 3, 1]
    Output: 0
    In this case, no transaction is done, i.e. max profit = 0.

中文描述:假設你有一個股票收益的list,只能買賣一次,求最大收益
解法:

 def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        minPrice = 9999999
        maxPro = 0
        for i in range(len(prices)):
            if prices[i] < minPrice:
                minPrice = prices[i]
            else:
                if prices[i] - minPrice > maxPro:
                    maxPro = prices[i] - minPrice
        return maxPro

解析:利用兩個變數記錄當前天時的最小值和所獲收益的最大值

Best Time to Buy and Sell Stock II

英文描述:Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

中文描述:上一道題的進階,就是說你可以操作買賣無數次求所獲收益最大值
解法:

 def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        return sum(max(prices[i+1] - prices[i], 0) for i in range(len(prices)-1))

解析: 每天買賣一次,收益為正就加,否則就加0

Valid Palindrome

英文描述:Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
例子:

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

中文描述: 對於給定的字串,不考慮空格、標點、大小寫,是不是迴文
解法:

 def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return True
        import re
        result = re.findall("[A-Za-z0-9]+", s)
        result = "".join(result).lower()
        for i in range(len(result)//2):
            if result[i] != result[-(i+1)]:
                return False
        return True

解析:使用正則匹配字串中字母。然後判斷這個字串是不是迴文

Single Number

英文描述: 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?
中文描述:使用O(n)的時間複雜度、O(1)空間複雜度,查詢列表中有沒有隻出現一次的值,其他的最多出現兩次
解法:

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        s_nums = sorted(nums)
        for i in range(0,len(s_nums)-1,2):
            if s_nums[i] != s_nums[i+1]:
                return s_nums[i]
        return s_nums[-1]

解析:對列表進行排序,然後遍歷步長為2

Linked List Cycle

英文描述: Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?
中文描述: 使用O(1)空間複雜度,判斷連結串列是否有環
解法:

 def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False   

解析:使用快慢“指標”

Min Stack

英文描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

例子:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

中文描述:設計一個棧
解法:

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.value = []

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.value.append(x)

    def pop(self):
        """
        :rtype: void
        """
        self.value.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.value[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.value)

解析: 使用python的列表模擬棧

Intersection of Two Linked Lists

英文描述:Write a program to find the node at which the intersection of two singly linked lists begins.
例子:

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
begin to intersect at node c1.

中文描述:找兩個連結串列的公共節點
解法:

def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA is None or headB is None:
            return None
        lcurA = headA
        la = 0
        while lcurA:
            la += 1
            lcurA = lcurA.next
        lb = 0
        lcurB = headB
        while lcurB:
            lb += 1
            lcurB = lcurB.next
        if la > lb:
            cha = la - lb
            curA = headA
            while cha != 0:
                curA = curA.next
                cha -= 1
            curB = headB
            if curA == curB:
                return curA
            while curA != curB:
                curA = curA.next
                curB = curB.next
                if curA == curB:
                    return curA
            return None
        elif la < lb:
            cha = lb - la
            curB = headB
            while cha != 0:
                curB = curB.next
                cha -= 1
            curA = headA
            if curA == curB:
                return curA
            while curA != curB:
                curA = curA.next
                curB = curB.next
                if curA == curB:
                    return curB
            return None
        else:
            curA = headA
            curB = headB
            while curA != curB:
                curA = curA.next
                curB = curB.next
                if curA == curB:
                    return curA
            if curA == curB:
                return curA
            return None

解析:長連結串列先走兩個連結串列長度差步,之後在一起走

Two Sum II - Input array is sorted

英文描述:Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.
例子:

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

中文描述:在一個列表中查詢兩個值得和等於目標值,並返回索引
解法:

def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        i = 0
        j = -1
        while i <= (len(numbers)) and abs(j) <= (len(numbers)):
            if numbers[i] + numbers[j] < target:
                i += 1
            elif numbers[i] + numbers[j] > target:
                j -= 1
            else:
                return [i+1, len(numbers) + j+1]
        return []

解析:直接從前後一起算,比較已經排好序的陣列

Excel Sheet Column Title

英文描述:Given a positive integer, return its corresponding column title as appear in an Excel sheet.
例子:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

中文描述:給定一個整型,返回所對應的字母
解法:

def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        result = []
        while n > 0:
            result.append(string.ascii_uppercase[(n - 1) % 26])
            n = (n - 1) // 26
        return "".join(reversed(result))

解析:emmmm….這道題我不會,,,現在還不懂,,,

Majority Element

英文描述:Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.
中文描述:判斷列表中出現 n/2向下取整次的數
解法:

def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = math.floor(len(nums) / 2)
        n_d = {}
        for i in nums:
            if i not in n_d:
                n_d[i] = 1
            else:
                n_d[i] = n_d.get(i) + 1
        for k in n_d:
            if n_d.get(k) > n:
                return k

解析:使用一個字典記錄數字出現的次數

Excel Sheet Column Number

英文描述:Given a column title as appear in an Excel sheet, return its corresponding column number.
例子:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 

中文描述:上面那道題的反向
解法:

def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s[::-1]
        sum1 = 0
        for exp, char in enumerate(s):
            sum1 += (ord(char) - 65 + 1) * (26 ** exp)
        return sum1

解析:依然不會。。。。。

Factorial Trailing Zeroes

英文描述:Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.
中文描述:返回n的階乘結尾有多少個0
解法:

def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        zeroCnt = 0
        while n > 0:
            n = n // 5
            zeroCnt += n
        return zeroCnt

解析:因為0的出現只跟5有關係

Rotate Array

英文描述:Rotate an array of n elements to the right by k steps.

例子:

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

中文描述:對列表進行平移
解法:

def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        k = k % n
        nums[:] = nums[n-k:] + nums[:n-k]

解析:使用列表的切片相加即可

Reverse Bits

英文描述:Reverse bits of a given 32 bits unsigned integer.
例子:

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

中文描述:將一個數的二進位制表示反轉,然後返回反轉後的整數
解法:

def reverseBits(self, n):
        b = []
        while n != 0:
            b.append(n % 2)
            n  //= 2
        if len(b) < 32:
            bu = [0] * (32-len(b))
            b.extend(bu)
        res = 0
        l = len(b)
        for i in range(len(b)):
            l -= 1
            res += b[i] * 2 **l
        return res

解析:求得當前數的二進位制,由於求得規則,所以不需要反轉,直接求整數就行,有一個地方小心,要保證列表的長度為32,不夠就補0

Number of 1 Bits

英文描述:Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
例子:

For example, the 32-bit integer11' has binary representation 00000000000000000000000000001011, so the function should return 3.

中文描述:返回一個整數轉成二進位制時有幾個1
解法:

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        b = []
        while n != 0:
            b.append(n % 2)
            n  //= 2
        if len(b) < 32:
            bu = [0] * (32-len(b))
            b.extend(bu)
        return b.count(1)

解析:求完二進位制數直接計算1的個數

House Robber

英文描述:You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
中文描述:搶劫房子,相鄰的不能搶,問收益最大,不能被抓
解法:

def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        last, now = 0,0
        for i in nums:
            last, now = now, max(last + i, now)
        return now

解析:現在手上的收益與搶不搶當前房子有關,是一個dp問題,上面的答案能A,可能是例子不好,比如【1,1,1,1,1,1】就會返回6,但是會被抓。。所以還需要思考

Happy Number

英文描述:Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
例子:

Example: 19 is a happy number

1**2 + 9**2 = 82
8**2 + 2**2 = 68
6**2 + 8**2 = 100
1**2 + 0**2 + 0**2 = 1

中文描述: 判斷一個數字是不是快樂數字,就是最後的數字位數的平方和是否等於1
解法:

def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        m = set()
        while n != 1:
            n_list = []
            while n != 0:
                n_list.append(int(n % 10) ** 2)
                n //= 10
            n = sum(n_list)
            if n in m:
                return False
            else:
                m.add(n)
        return True

解析:將求得的數字放到一個set中,如果出現在set中就說明不是,否則就是

Remove Linked List Elements

英文描述:Remove all elements from a linked list of integers that have value val.
例子:

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

中文描述:刪除連結串列中特定的值
解法:

def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        handle = ListNode(-1)
        handle.next = head
        prev, curr = handle, handle.next
        while curr:
            if curr.val==val:
                prev.next = curr.next
                curr = prev.next
                continue
            prev, curr = prev.next, curr.next
        return handle.next         

解析:主要防止後續連結串列丟失就行了

Count Primes

英文描述:Count the number of prime numbers less than a non-negative number, n.
中文描述:求小於n的質數的個數
解法:

def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2:
            return 0 
        prime = [True] * n
        prime[:2] = [False, False]
        for base in range(2, int((n - 1) ** 0.5) + 1):
            if prime[base]:
                prime[base ** 2::base] = [False] * len(prime[base ** 2::base])
        return sum(prime)

解析:假設都是質數,遍歷列表,如果當前值是質數的它的倍數都不是質數。。。

Isomorphic Strings

英文描述:Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
例子:

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.

中文描述:判斷兩個字串是否形式一樣
解法:

def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        def s2i(s):
            s_list = list(s)
            s_dict = {}
            for i in s_list:
                if i not in s_dict:
                    s_dict[i] = len(s_dict) + 1
            return "".join([str(s_dict.get(i)) for i in s_list])
        return s2i(s) == s2i(t)        

解析:將字串轉成數字字串

Reverse Linked List

英文描述:Reverse a singly linked list.
中文描述:反轉連結串列
解法:

def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head
        if head.next == None:
            return head
        newNode = ListNode(-1)
        wei = newNode.next
        cur = head
        while cur:
            node = cur
            cur = cur.next
            node.next = None
            newNode.next = node
            node.next = wei
            wei = node
        return newNode.next

解析:注意連結串列後續不丟失

Contains Duplicate

英文描述:Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
中文描述:判斷列表是否有重複值
解法:

def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(nums) != len(set(nums))

解析:利用集合和list的性質

Contains Duplicate II

英文描述:Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
中文描述:在列表中找到兩個相等的值,他們索引相差不大於k
解法:

def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic = {}
        for i, v in enumerate(nums):
            if v in dic and i - dic[v] <= k:
                return True
            dic[v] = i
        return False

解析:利用字典記錄值得索引

Implement Stack using Queues

英文描述:Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

中文描述:利用佇列實現棧
解法:

class MyStack(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.v = []


    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        self.v.append(x)

    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        return self.v.pop()

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        return self.v[-1]

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        if len(self.v) == 0:
            return True
        else:
            return False

解析:python的列表可以實現佇列的功能

Invert Binary Tree

英文描述: Invert Binary Tree
例子:

Invert a binary tree.
     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1

中文描述:反轉二叉樹
解法:

 def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                node.left, node.right = node.right, node.left
                stack += node.left, node.right
        return root        

解析:利用棧實現

Power of Two

英文描述:Given an integer, write a function to determine if it is a power of two.
中文描述:判斷一個數是不是2的次方
解法:

def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 0:
            return False
        if n == 1:
            return True
        while n != 1:
            if n % 2 == 0:
                n //= 2
            else:
                return False
        return True

解析:利用2的次方的性質

Implement Queue using Stacks

英文描述:Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

中文描述:利用棧實現佇列
解法:

class MyQueue(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.inStack, self.outStack = [], []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.inStack.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        self.move()
        return self.outStack.pop()

    def peek(self):
        """
        :rtype: int
        """
        self.move()
        return self.outStack[-1]

    def empty(self):
        """
        :rtype: bool
        """
        return (not self.inStack) and (not self.outStack) 

    def move(self):
        """
        :rtype nothing
        """
        if not self.outStack:
            while self.inStack:
                self.outStack.append(self.inStack.pop())

解析:利用兩個棧可以實現佇列

Palindrome Linked List

英文描述:Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?
中文描述:使用O(n)的時間複雜度和O(1)的空間複雜度判斷連結串列是否是迴文連結串列
解法:

 def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """ 
        fast = slow = head
        # find the mid node
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        # reverse the second half
        node = None
        while slow:
            nxt = slow.next
            slow.next = node
            node = slow
            slow = nxt
        # compare the first and second half nodes
        while node: # while node and head:
            if node.val != head.val:
                return False
            node = node.next
            head = head.next
        return True

解析:從中間的值之後開始反轉後半部的連結串列,然後判斷前後是否相等。

第二週結束了,,好快啊,不過可以感覺到這周刷題比上週快了許多,而且順利了許多,看來刷題還是要練習的,加油!!!希望以後越來越順,哈哈哈