使用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

解析:从中间的值之后开始反转后半部的链表,然后判断前后是否相等。

第二周结束了,,好快啊,不过可以感觉到这周刷题比上周快了许多,而且顺利了许多,看来刷题还是要练习的,加油!!!希望以后越来越顺,哈哈哈

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值