LeetCode Online Judge
https://leetcode.com/
LeetCode题解
https://github.com/soulmachine/leetcode
1.The Best Time to Buy and Sell Stocks [52ms]
#方法1: 用一个变量记录最小价格
#遍历时取之前利益最大值,和目前差两个之间的最大值
#因为是正序遍历,所以不用担心卖出价格在买出前
class Solution(object):
def maxProfit(self, prices):
min_price = 100000
max_profit = 0
for i in prices:
min_price = min(min_price, i)
max_profit = max(max_profit, i - min_price)
return max_profit
2. Contains Duplicate [70ms]
#方法1:内置set [70ms]
#方法2:一个个检测 [80ms]
#方法3:哈希表,会超时[1096ms]
class Solution(object):
def containsDuplicate(self, nums):
s = set(nums)
if len(s) == len(nums):
return False
else:
return True
class Solution(object):
def containsDuplicate(self, nums):
s = set()
for i in nums:
if i in s:
return True
else:
s.add(i)
return False
class Solution(object):
def containsDuplicate(self, nums):
s = {}
for i in nums:
if str(i) not in s.keys():
s[str(i)] = 1
else:
return True
return False
3.Cotains Duplicate II [64ms]
#这道题本人超时n次
#连先判断它不在哈希表,后处理都超时
#最短距离只会出现在相邻的数
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
hashtable = {}
for i in range(len(nums)):
#这属于少数
if nums[i] in hashtable:
if i - hashtable[nums[i]] <= k:
return True
#多情况直接执行,省去判断
hashtable[nums[i]] = i
return False
4.Majority Element [64ms]
class Solution(object):
def majorityElement(self, nums):
h = {}
for i in nums:
if i in h:
h[i] += 1
else:
h[i] = 1
for i in h:
if h[i] > int(len(nums) / 2) :
return i
5.Merge Sorted Array [48ms]
#方法1:先膜拜一下这么简单的写法[48ms]
#方法2:倒叙插入,不需要额外储存
class Solution(object):
def merge(self, nums1, m, nums2, n):
nums1[m:] = nums2[:n]
nums1.sort()
6.Move Zeros [72ms]
class Solution(object):
def moveZeroes(self, nums):
index = length = len(nums)
i = 0
while i < index:
if nums[i] == 0:
del nums[i]
index -= 1
else:
i += 1
for i in range(length-index):
nums.append(0)
7.Pascal’s Triangle [56ms]
class Solution(object):
def generate(self, numRows):
ans = []
for i in range(numRows):
tmp = []
for j in range(i+1):
if j == 0 or j == i:
tmp.append(1)
else:
tmp.append(ans[i-1][j-1] + ans[i-1][j])
ans.append(tmp)
return ans