注意,答案只是代表是他人写的代码,正确,但不一定能通过测试(比如超时),列举出来只是它们拥有着独到之处,虽然大部分确实都比我的好
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.
思路
看起来就是求有顺序的最大最小值。
还记得之前的合并排序吗,哈哈哈
好像不太对,好像不用那么复杂???(反正我肯定不会去用2次遍历的)
写了半天还是不对QAQ
我tm用合并排序真是脑子里进了水!!!
我们,走了一些弯路
还是有些类似与最大子数组的做法,只不过判断条件有些区别
解答
class Solution(object):
def maxProfit(self, A):
"""
:type prices: List[int]
:rtype: int
"""
newbuy=0
sell=0
buy=0
smax =0
for start in range(len(A)):
if A[start] > A[sell] :
sell = start
smax = A[sell]- A[buy]
if A[start] < A[newbuy]:
newbuy = start
if A[start]-A[newbuy] > smax:
buy = newbuy
sell = start
smax = A[sell]- A[buy]
return max(smax,0)
答案
def maxProfit(prices):
max_profit, min_price = 0, float('inf')#正无穷
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
思考
思考的不够细致,只需要最小价格和最大差值这两个量,因为最后返回的是差值,所以位置之类的不重要,我的思维还是很有局限性。
重写
感受到正无穷的好处了,不需要判断list是否为空
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) != 0 :
s_min = prices[0]
smax =0
for price in prices:
s_min = min(s_min, price)
smax = max(smax, price - s_min)
return smax
Add Strings
题目
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路
不让使用内置函数啊
不太对啊,没办法向c那样直接 - ‘0’啊,应该有转换函数吧
ord chr
返回值怎么写我都不知道
为什么返回的是 /u 什么什么的
解答
真是各种小bug不断,发现返回/u是chr函数 的问题,所以只能用str函数了
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
length = max(len(num1),len(num2))
l=[]
cc =0
for i in range(1,length+1):
if len(num1) >= i:
n1 = ord(num1[-i]) - ord('0')
else :
n1=0
if len(num2) >= i:
n2 = ord(num2[-i]) - ord('0')
else :
n2=0
x = n1+n2+cc
if x >= 10:
l.append(str(x-10))
cc=1
else:
l.append(str(x))
cc=0
if cc ==1:
l.append(str(1))
return ''.join(l[::-1])
答案
def addStrings(self, num1, num2):
z = itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0')
res, carry, zero2 = [], 0, 2*ord('0')
for i in z:
cur_sum = ord(i[0]) + ord(i[1]) - zero2 + carry
res.append(str(cur_sum % 10))
carry = cur_sum // 10
return ('1' if carry else '') + ''.join(res[::-1])
思考
查了下资料才知道第一个函数是啥,而且循环内部的式子也比我的简练的多
重写
算了再贴一份代码吧,我重写最高也就是这样的了
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1, num2 = list(num1), list(num2)
carry, res = 0, []
while len(num2) > 0 or len(num1) > 0:
n1 = ord(num1.pop())-ord('0') if len(num1) > 0 else 0
n2 = ord(num2.pop())-ord('0') if len(num2) > 0 else 0
temp = n1 + n2 + carry
res.append(temp % 10)
carry = temp // 10
if carry: res.append(carry)
return ''.join([str(i) for i in res])[::-1]
Add Two Numbers
题目
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路
看起来非常不难
解答
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l =head = ListNode(0)
carry = 0
while l1 or l2:
temp =carry
if l1:
temp += l1.val
l1 = l1.next
if l2:
temp += l2.val
l2 = l2.next
l.next= l = ListNode(temp % 10)
carry = temp/10
if carry:
l.next = ListNode(1)
return head.next
答案
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
n.next = ListNode(val)
n = n.next
return root.next
思考
哦?
Arranging Coins
题目
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form the following rows:
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3.
思路
看起来确实蛮简单的,一遍循环解决的事情
解答
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i=0
while True:
if n-i < 0:
return i - 1
elif n-i == 0:
return i
else:
n = n - i
i += 1
打败了3%的人???
答案
return int((math.sqrt(1+n*8)-1)/2)
思考
这个答案有些过分了
方法:数学
问题基本上是要求运行总和小于或等于“n”的连续数的最大长度。换句话说,找到满足以下条件的x
:
1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n
sum_ {i = 1} ^ xi <= n
运行总和可以简化,
(x *(x + 1))/ 2 <= n
使用二次方程式,“x”被评估为,
x = 1/2 *(-sqrt(8 * n + 1)-1)
(不适用)或`x = 1/2 (sqrt(8 n + 1)-1)
是解一元二次方程啊
方法二
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i = 1
while n >= 0:
n -= i
i += 1
return (i-2)
相对好懂的一种
重写
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
i=0
while n>=i:
n -= i
i += 1
return i-1
感觉还是这样吧
Climbing Stairs
题目
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
思路
类似于之前那个本来用dfs后来用数组的那个啊
解答
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
c = [0]+[1]+[2]+[0]*(n-2)
for i in range(3,n+1):
c[i] = c[i-2] + c[i-1]
return c[n]
写出来才发现这不是斐波那契数列吗
呃。。打败了8%的人
既然如此
if n == 1 :
return 1
a,b=1,2
for i in range(3,n+1):
b,a=a+b,b
return b
打败2%的人,我擦勒
再提交一次就30%了…呃
答案
def climbStairs1(self, n):
if n == 1:
return 1
if n == 2:
return 2
return self.climbStairs(n-1)+self.climbStairs(n-2)
看起来确实不错,不过我试了一下,超时了哈哈