Skip to content

Commit 37b4b95

Browse files
committed
更新部分
1 parent bf8c766 commit 37b4b95

29 files changed

+1277
-117
lines changed

Python/array-partition-i.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,23 @@ def arrayPairSum(self, nums):
1818
:type nums: List[int]
1919
:rtype: int
2020
"""
21-
# 思路一: 本问题相当于从小大到排序后,所有偶数之和
21+
# Approach one
22+
# ans = 0
23+
# new_nums = sorted(nums)
24+
# for i in range(0,len(new_nums),2):
25+
# ans += new_nums[i]
26+
# return ans
27+
28+
# Approach two 进一步简化代码,无需新数组
29+
# ans = 0
30+
# nums.sort()
31+
# for i in nums[::2]:
32+
# ans += i
33+
# return ans
34+
35+
# Approach three: 本问题相当于从小大到排序后,所有偶数之和
2236
# return sum([num for i, num in enumerate(sorted(nums)) if i % 2 == 0])
2337

24-
# 思路二: 利用数组切片,进一步简化操作
38+
# Approach Four: 利用数组切片,进一步简化操作
2539
# python 内置的sorted() 的平均/最坏时间复杂度均为 $O(nlog_2(n))$, 可以说是非常威武了。
2640
return sum(sorted(nums)[::2])
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
4+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
5+
6+
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
7+
8+
Example 1:
9+
10+
Input: [7,1,5,3,6,4]
11+
Output: 7
12+
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
13+
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
14+
Example 2:
15+
16+
Input: [1,2,3,4,5]
17+
Output: 4
18+
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
19+
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
20+
engaging multiple transactions at the same time. You must sell before buying again.
21+
Example 3:
22+
23+
Input: [7,6,4,3,1]
24+
Output: 0
25+
Explanation: In this case, no transaction is done, i.e. max profit = 0.
26+
27+
'''
28+
29+
30+
class Solution(object):
31+
def maxProfit(self, prices):
32+
"""
33+
:type prices: List[int]
34+
:rtype: int
35+
"""
36+
37+
# 从问题的本质入手,而不是观察示例序列的规律。
38+
# 优化目标是总的赚钱利润,用贪心算法,只要是相隔两天有盈利就操作,即可得到最大利润(现实环境没有这么“干净”的问题)
39+
maxPro = 0
40+
for i in range(1,len(prices)):
41+
if prices[i] > prices[i-1]:
42+
maxPro += prices[i] - prices[i-1]
43+
return maxPro
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
3+
4+
Example:
5+
6+
Input: s = 7, nums = [2,3,1,2,4,3]
7+
Output: 2
8+
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
9+
Follow up:
10+
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
11+
12+
13+
'''
14+
15+
16+
class Solution:
17+
def minSubArrayLen(self, s, nums):
18+
"""
19+
:type s: int
20+
:type nums: List[int]
21+
:rtype: int
22+
"""
23+
# Approach one
24+
# left = 0
25+
# ans = 10000000
26+
# for i in range(len(nums)):
27+
# while sum(nums[left:i+1]) >= s:
28+
# ans = min(ans, i - left + 1)
29+
# left += 1
30+
# return ans if ans != 10000000 else 0 # 处理没有答案的特殊情况
31+
32+
33+
# Approach two
34+
left,tmp,ans = 0,0,10000000
35+
for i in range(len(nums)):
36+
tmp += nums[i]
37+
while tmp >= s: # 减少重复的求和操作
38+
if ans > i - left +1:
39+
ans = i - left +1 # min()、max() 函数耗费时间过多
40+
tmp -= nums[left]
41+
left += 1
42+
return ans if ans != 10000000 else 0 # 处理没有答案的特殊情况
43+
44+
45+
46+
47+
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
3+
4+
Given linked list -- head = [4,5,1,9], which looks like following:
5+
6+
7+
8+
Example 1:
9+
10+
Input: head = [4,5,1,9], node = 5
11+
Output: [4,1,9]
12+
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
13+
Example 2:
14+
15+
Input: head = [4,5,1,9], node = 1
16+
Output: [4,5,9]
17+
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
18+
Note:
19+
20+
The linked list will have at least two elements.
21+
All of the nodes' values will be unique.
22+
The given node will not be the tail and it will always be a valid node of the linked list.
23+
Do not return anything from your function.
24+
'''
25+
26+
27+
# Definition for singly-linked list.
28+
# class ListNode(object):
29+
# def __init__(self, x):
30+
# self.val = x
31+
# self.next = None
32+
33+
class Solution(object):
34+
def deleteNode(self, node):
35+
"""
36+
:type node: ListNode
37+
:rtype: void Do not return anything, modify node in-place instead.
38+
"""
39+
40+
node.val = node.next.val
41+
node.next = node.next.next

Python/diagonal-traverse.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
'''
2+
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
3+
4+
5+
6+
Example:
7+
8+
Input:
9+
[
10+
[ 1, 2, 3 ],
11+
[ 4, 5, 6 ],
12+
[ 7, 8, 9 ]
13+
]
14+
15+
Output: [1,2,4,7,5,3,6,8,9]
16+
17+
Explanation:
18+
19+
20+
21+
Note:
22+
23+
The total number of elements of the given matrix will not exceed 10,000.
24+
25+
'''
26+
27+
28+
class Solution:
29+
def findDiagonalOrder(self, matrix):
30+
"""
31+
:type matrix: List[List[int]]
32+
:rtype: List[int]
33+
"""
34+
# Approach one 效率低
35+
# if matrix == []: return []
36+
# ans = []
37+
# row,col = len(matrix), len(matrix[0])
38+
# if row == 1: return matrix[0]
39+
# for num in range(row + col):
40+
# if num % 2 == 0:
41+
# for i in range(num+1):
42+
# if i >= col:
43+
# break
44+
# if num - i >= row:
45+
# continue
46+
# ans.append(matrix[num - i][i])
47+
# else:
48+
# for i in range(num+1):
49+
# if i >= row:
50+
# break
51+
# if num - i >= col:
52+
# continue
53+
# ans.append(matrix[i][num - i])
54+
# return ans
55+
56+
57+
# Approach two 不是用循环,免去遍历多余的数, 时间效率前100%
58+
if matrix == []: return []
59+
row,col = len(matrix), len(matrix[0])
60+
ans = []
61+
number = row * col
62+
i = j = 0
63+
up = True
64+
while number:
65+
number -= 1
66+
ans.append(matrix[i][j])
67+
if up:
68+
if j == col - 1:
69+
i += 1
70+
up = False
71+
elif i == 0:
72+
j += 1
73+
up = False
74+
else:
75+
i -= 1
76+
j += 1
77+
else:
78+
if i == row - 1:
79+
up = True
80+
j += 1
81+
elif j == 0:
82+
i += 1
83+
up = True
84+
else:
85+
i += 1
86+
j -= 1
87+
return ans
88+
89+
90+

Python/find-pivot-index.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'''
2+
Given an array of integers nums, write a method that returns the "pivot" index of this array.
3+
4+
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
5+
6+
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
7+
8+
Example 1:
9+
Input:
10+
nums = [1, 7, 3, 6, 5, 6]
11+
Output: 3
12+
Explanation:
13+
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
14+
Also, 3 is the first index where this occurs.
15+
Example 2:
16+
Input:
17+
nums = [1, 2, 3]
18+
Output: -1
19+
Explanation:
20+
There is no index that satisfies the conditions in the problem statement.
21+
Note:
22+
23+
The length of nums will be in the range [0, 10000].
24+
Each element nums[i] will be an integer in the range [-1000, 1000].
25+
26+
'''
27+
28+
29+
class Solution:
30+
def pivotIndex(self, nums):
31+
"""
32+
:type nums: List[int]
33+
:rtype: int
34+
"""
35+
36+
# Approach one 低效的方法
37+
# for i in range(len(nums)):
38+
# if sum(nums[:i]) == sum(nums[i+1:]):
39+
# return i
40+
# return -1
41+
42+
# Approach two
43+
# 注意,中心索引可以为第一个元素,左侧没有元素,其和默认为0
44+
# leftsum = 0
45+
# rightsum = sum(nums)
46+
# for i in range(len(nums)):
47+
# if i >= 1: leftsum += nums[i-1]
48+
# rightsum -= nums[i]
49+
# if leftsum == rightsum: return i
50+
# return -1
51+
52+
53+
# Approach three 将中心索引分别算进左右的元素之和,减少判断语句的使用
54+
leftsum, rightsum = 0, sum(nums)
55+
for i in range(len(nums)):
56+
leftsum += nums[i]
57+
if leftsum == rightsum: return i
58+
rightsum -= nums[i]
59+
return -1

Python/implement-strstr.py

-4
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,3 @@ def strStr(self, haystack, needle):
6565
if haystack[i:i+len(needle)]==needle: # 字符串切片操作可以直接比较一个子串,不用每个字符都比较
6666
return i # i 为 0 的时候, haystack[0:0] 表示为 0
6767
return -1
68-
69-
70-
71-

Python/largest-number-at-least-twice-of-others.py

+34-6
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,43 @@ def dominantIndex(self, nums):
3232
:type nums: List[int]
3333
:rtype: int
3434
"""
35-
# Approach #1
35+
# Approach one 重复遍历,效率偏低
36+
# max_num = max_id = 0
37+
# for i,num in enumerate(nums):
38+
# if num > max_num:
39+
# max_num = num
40+
# max_id = i
41+
# nums.remove(max_num)
42+
# if nums != [] and max_num < max(nums)*2: return -1 # 防止列表只有一个元素
43+
# return max_id
44+
45+
46+
# Approach two 简化代码,但仍重复遍历
47+
# if len(nums) == 1 : return 0
48+
# max_num = max(nums)
49+
# max_id = nums.index(max_num)
50+
# nums.remove(max_num)
51+
# if max_num >= max(nums) * 2: return max_id
52+
# return -1
53+
54+
55+
# Approach three
3656
# max_num = max(nums)
3757
# for num in nums:
3858
# if 2*num > max_num and num != max_num:
3959
# return -1
4060
# return nums.index(max_num)
4161

42-
# Approach #2
43-
max_num = max(nums)
44-
max_loc = nums.index(max_num)
45-
nums[max_loc] = 0
46-
return max_loc if max_num >= max(nums) *2 else -1
62+
# Approach four
63+
# max_num = max(nums)
64+
# max_loc = nums.index(max_num)
65+
# nums[max_loc] = 0 # 通过置零,而不是删除,解决只有一个元素的情况。
66+
# return max_loc if max_num >= max(nums) *2 else -1
67+
68+
# Approach five 只需一次排序,效率最高
69+
if len(nums) > 1:
70+
max_nums = sorted(nums)
71+
if max_nums[-1] >= max_nums[-2] * 2:
72+
return nums.index(max_nums[-1])
73+
return -1
74+
return 0 # 只有一个元素时需要特殊处理

0 commit comments

Comments
 (0)