【二】Leetcode之Python刷题之路

1. Move Zeros

给一个数组,将数组里的0全部移到数组最后。
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

LeetCode里很多题目要求”do this in-place”,通俗的理解就是算法输出结果覆盖算法的输入,这样做可以节省内存。
我的代码实现如下:

class Solution(object):
    def moveZeroes(self, nums):
        for i in range(nums.count(0)):
            nums.remove(0)
        nums.extend([0]*count0)

思路比较简单,由于remove(x)函数每次只能删除第一个遇到的x,因此这里首先将所有0移除,然后在最后用extend()的方法将0添加到nums最后。

2. 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.

  我最开始的思路是遍历nums中所有的元素,然后count每个元素出现的次数,提交代码的时候被拒绝了,结论是:”Runtime Limited Error”超时了。确实,这样的实现方法时间复杂度为 O(n2) O ( n 2 ) ,太耗资源且粗暴无脑。后来通过set()函数将nums去重,然后遍历计算每个元素出现的次数是否大于n/2,最终代码提交成功,代码如下:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums_set = set(nums)
        for each in nums_set:
            if nums.count(each) > (len(nums)/2):
                return each

看了Discuss里别人提交的代码,真的被折服了。
Approach 2:
有个算法非常简单,因为该数组中必有一个数字出现超过N/2次,因此如果将该数组排序,则第N//2个元素必为我们想要的结果。

class Solution:
    def majorityElement(self, nums):
        nums.sort()
        return nums[len(nums)//2]

Approach 3:
另外一个时间、空间复杂度只有O(n)的算法就是利用Hash表。

class Solution:
    def majorityElement(self, nums):
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get) #这里max函数里定义key=counts.get,即出现最多次数的'键'

Python中collections模块详解请移步:Python标准库——collections模块的Counter类

3. 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.

  这道题我的解题思路比较简单粗暴,但是无奈提交代码的时候还是”Runtime Limited Error”处理时间超时了,代码如下,时间复杂度 O(n2) O ( n 2 )

class Solution(object):
    def maxProfit(self, prices):
        length = len(prices)
        maxprofit = 0
        for each in prices:
            for i in range(prices.index(each)+1,length):
                if prices[i]-each > maxprofit:
                    maxprofit = prices[i]-each
        if maxprofit > 0:
            return maxprofit
        else:
            return 0

正确答案:

class Solution(object):
    def maxProfit(self, prices):
        maxprofit = 0
        minprice = prices[0]
        for i in range(1,len(prices)):
            if price[i] < minprice:
                minprice = price[i]
            maxprofit = max(maxprofit,price[i] - minprice)
        return maxporfit

你可能感兴趣的:(Python)