-
第88题(简单):Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
注意:
nums1的个数为m, nums2 的个数为n;
nums1中有足够的容量,容纳nums2 (用0表示容纳nums2)
例子:Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3Output: [1,2,2,3,5,6]
代码:
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums2[n-1] > nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n = n -1
else:
nums1[m-1], nums1[n+m-1] = nums1[n+m-1], nums1[m-1]
m = m-1
if m == 0 and n > 0 :
nums1[:n] = nums2[:n]
-
第112题(简单):Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
Note: A leaf is a node with no children(叶子节点是指没有子节点的节点。).
示例:
给定如下二叉树,以及目标和 sum = 22,
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
代码:# class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if root is None: return False if root.left is None and root.right is None and root.val == sum: return True else: return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
-
第118题(简单) ,Pascal’s Triangle 杨辉三角形
Given a non-negative integer numRows,
generate the first numRows of Pascal’s triangle.
例子:
Input: 5
Output:
主要思想:杨辉三角。起始和末尾都是1。中间的数,是上一排的前一个索引的数字,和当前索引的数字的相加。
代码:
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
result = []
for i in range(numRows):
result.append([])
for j in range(i+1): #每一行的元素
if j in (0,i):
result[i].append(1)
else:
result[i].append(result[i-1][j-1] + result[i-1][j])
return result
- 第119题(简单):Pascal’s Triangle II (118题的进阶)
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
给出一个索引数字,返回那一层的数。
Example:
Input: 3
Output: [1,3,3,1]
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = [1] + [0]*rowIndex
for i in range(rowIndex):
for j in range(i+1, 0, -1):
result[j] = result[j] + result[j-1]
return result
- 第121题(简单):Best Time to Buy and Sell Stock (只允许一次交易)
数组i位置代表第i天股票的价格,只允许,买一次,卖一次,买卖不可以在同一天,且必须先买再卖,求最大利润。
(1) Example 1:
Input: [7,1,5,3,6,4]
Output: 5
解释: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
(2) Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
主要思想:去找到在前一段区间内最小的数,和后一段区间内最大的数,二者之差即为最大收益。
怎么去寻找最小值?用迭代的方式,通过遍历数组,我们可以设置一个min变量来保存当前时刻的最小值,最大收益值则是不断用当前值减去最小值,不断的更新min值以及最大收益值。
代码:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_price, max_profit = float("inf") , 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
- 第122题(简单):Best Time to Buy and Sell Stock II (可允许多次交易)
数组i位置代表第i天股票的价格,可允许多次交易,买-卖-买-卖,(必须先卖掉,才能重新买)
求最大利润。
主要思路:遍历数组,计算全部第二天比前一天价格高的值,加起来就是最后的最大收益。
(1) Example1:
Input: [7,1,5,3,6,4]
Output: 7
解释: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3
(2) Example2:
Input: [1,2,3,4,5]
Output: 4
解释: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
(3)Example3:
Input: [7,6,4,3,1]
Output: 0
解释: In this case, no transaction is done, i.e. max profit = 0.
代码:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
total = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
total += prices[i] - prices[i-1]
return total
-
第125题(简单):Valid Palindrome 有效的回文串
回文串:正读和反着读都一样的。
判断一个字符串是否是回文字符串,只考虑字母和数字,并且忽略大小写。
注意点: 空字符串在这里也定义为回文串(1) Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true(2)Example 2:
Input: “race a car”
Output: false
主要思路:
- 设两个指针,一个头一个尾,判断是否相等
- 判断是否是 字母/数字:isalnum() ,去掉不是字母/数字的
- 都改为小写
代码:
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
i, j = 0, len(s)-1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
return True
- 第136题(简单):Single Number
一个非空的数组中,有一个数据只出现一次,其他数据都出现两次。
找到那个只出现一次的数。
思路:位运算(异或),只要循环异或,出现两次的都变成0了,最后只剩下出现一次的single number
异或:两个相同的数字异或等于0。任意数字与0异或都等于它本身。
(1)Example 1:
Input: [2,2,1]
Output: 1
(2)Example 2:
Input: [4,1,2,1,2]
Output: 4
代码:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for num in nums:
ans ^= num
return ans
- 第141题(简单): Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which
represents the position (0-indexed) in the linked list where tail connects to.
If pos is -1, then there is no cycle in the linked list.
注意:题目是只给了head, 并没有给pos
主要思路:设2个指针,1个fast(走两步),1个slow(走一步)。只要存在cycle,它们就一定会重叠 。
代码:
# 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
"""
fast, slow = head, head
while fast and fast.next: # 如果没有cycle,fast肯定是会先结束的
fast = fast.next.next # fast跳两个
slow = slow.next # slow 跳一个
if fast == slow:
return True
return False
- 第160题(简单). Intersection of Two Linked Lists 求两个链表的交点
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
(1)Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
(2)Example2:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p1, p2 = headA, headB
while p1 != p2:
if not p1:
p1 = headB
else:
p1 = p1.next
if not p2:
p2 = headA
else:
p2 = p2.next
return p1