题目编号: 118、119、121、122、125、136、141
118. 杨辉三角
我的解法:
两个数组,now用来记录当前行数据,pre用来记录上一行的数据
首先对每一行设为全1,根据杨辉三角的特点,从第三行起,第二个元素开始,到倒数第二个元素为止,当前元素i等于上一行的i-1号元素和i号元素的和
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
result = []
for i in range(numRows):
now = [1]*(i+1)
if i >= 2:
for n in range(1,i):
now[n] = pre[n-1]+pre[n]
result += [now]
pre = now
return result
119. 杨辉三角 II
我的解法:
思路同上题,返回结果时返回now数组即可
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = []
for i in range(rowIndex+1):
now = [1]*(i+1)
if i >= 2:
for n in range(1,i):
now[n] = pre[n-1]+pre[n]
result += [now]
pre = now
return now
121. 买卖股票的最佳时机
我的解法:
假设给定的数组为:
[7, 1, 5, 3, 6, 4]
如果我们在图表上绘制给定数组中的数字,我们将会得到:
维持两个变量——minprice 和 maxprofit,它们分别对应迄今为止所得到的最小的谷值和最大的利润(卖出价格与最低价格之间的最大差值)
先找到一个最小谷底的然后继续找最大的峰值,这期间如果找到比之前找到的谷底更小的值,那么就更换谷底的值,然后再找最高的峰值,然后比较差值是否比之前的大,如果大就替换不然就找类似的进行判断
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minPrice = sys.maxsize
maxProfit = 0
for i in range(0,len(prices)):
if prices[i] < minPrice:
minPrice = prices[i]
elif prices[i] - minPrice > maxProfit:
maxProfit = prices[i] - minPrice
return maxProfit
122. 买卖股票的最佳时机 II
我的解法:
一次遍历
从下标为1的元素开始遍历,若当前元素的值大于上一个元素的值,则说明收益还能增加,则maxProfit加上两者之间的差值,直至遍历结束,所得结果即为最大收益
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxProfit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
maxProfit += prices[i] - prices[i-1]
return maxProfit
125. 验证回文串
我的解法:
双指针法
左指针从头开始向后扫描,右指针从后开始向前扫描,若扫描中遇到不是字母或者数字字符的字符,跳过当前字符;将左右指针所指向的两个字符的小写形式相比较,若不相同,则返回False;当右指针指向左指针的左侧后,若未返回False,则说明为回文串
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = 0
right = len(s)-1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
136. 只出现一次的数字
我的解法:
异或:
交换律:a ^ b ^ c <=> a ^ c ^ b
任何数于0异或为任何数 0 ^ n => n
相同的数异或为0: n ^ n => 0
出现两次的数字经过异或结果为0,故最终剩余的结果就为只出现一次的数字
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for num in nums:
a = a ^ num
return a
141. 环形链表
我的解法:
快慢指针法
慢指针每次移动一步,而快指针每次移动两步。
如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false。
如果列表中存在环,则快指针会追上慢指针,此时我们可以返回true
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
p_slow = head
p_fast = head.next
while p_fast and p_fast.next:
p_slow = p_slow.next
p_fast = p_fast.next.next
if p_slow == p_fast:
return True
return False