1. Move Zeros

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)

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(n2)
，太耗资源且粗暴无脑。后来通过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

Approach 2:

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

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类
<http://www.pythoner.com/205.html>

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(
n2)。
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]-eachif maxprofit > 0: return
maxprofitelse: 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

30天阅读排行