KK's blog

每天积累多一些

0%

LeetCode



Given a rows x cols binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing only 1‘s and return its area.

Example 1:



Input: matrix = [[“1”,”0”,”1”,”0”,”0”],[“1”,”0”,”1”,”1”,”1”],[“1”,”1”,”1”,”1”,”1”],[“1”,”0”,”0”,”1”,”0”]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.


Example 2:

Input: matrix = [[“0”]]
Output: 0


Example 3:

Input: matrix = [[“1”]]
Output: 1


Constraints:

rows == matrix.length cols == matrix[i].length
1 <= row, cols <= 200 matrix[i][j] is '0' or '1'.

题目大意:

0-1矩阵求全部都是1的最大的子矩阵

解题思路:

类似于LeetCode 084 Largest Rectangle in Histogram,按每行生成连续1的直方图,求最大矩形面积。然后逐行调用L084的方法。

解题步骤:

N/A

注意事项:

  1. 由于L084的方案是修改原数组,所以不能直接调用,必须修改L084的方法,copy一份数组再往首尾插入0.

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def maximalRectangle(self, matrix: List[List[str]]) -> int:
heights, res = [0] * len(matrix[0]), 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == '0':
heights[j] = 0
else:
heights[j] += 1
area = self.largestRectangleArea(heights)
res = max(res, area)
return res

def largestRectangleArea(self, height_list: List[int]) -> int:
stack, res = [], 0
heights = list(height_list)
heights.insert(0, 0) # remember
heights.append(0)
for i in range(len(heights)):
while stack and heights[i] < heights[stack[-1]]:
index = stack.pop()
res = max(res, (i - stack[-1] - 1) * heights[index]) # remember i - stack[-1] - 1 not i - index
stack.append(i)
return res

算法分析:

时间复杂度为O(nm),空间复杂度O(m), n, m分别为行数和列数

LeetCode



Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]


Example 2:

Input: nums = [0]
Output: [[],[0]]


Constraints:

1 <= nums.length <= 10 -10 <= nums[i] <= 10

题目大意:

求所有子集,元素可能相同,不能含相同子集

解题思路:

类似于L078 Subsets,但元素可能相同,所以排序且比较相邻元素,若相等就跳过

解题步骤:

N/A

注意事项:

  1. 元素可能相同,所以排序且比较相邻元素,若相等就跳过

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
nums.sort()
res = [[]]
self.dfs(nums, 0, [], res)
return res

def dfs(self, nums, st, path, res):
if st == len(nums):
return
for i in range(st, len(nums)):
if i > st and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
res.append(list(path))
self.dfs(nums, i + 1, path, res)
path.pop()

算法分析:

时间复杂度为O(nx2n),空间复杂度O(n)

LeetCode



You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.

In one move, you can either:

Increment the current integer by one (i.e., x = x + 1). Double the current integer (i.e., x = 2 * x).

You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.

Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.

Example 1:

Input: target = 5, maxDoubles = 0
Output: 4
Explanation: Keep incrementing by 1 until you reach target.


Example 2:

Input: target = 19, maxDoubles = 2
Output: 7
Explanation: Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19


Example 3:

Input: target = 10, maxDoubles = 4
Output: 4
Explanation:Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10


Constraints:

1 <= target <= 10<sup>9</sup> 0 <= maxDoubles <= 100

题目大意:

加1或者乘2达到target,乘2有次数限制,求到达target的最小步数

DFS解题思路(推荐):

由于是最值,一开始用DP,但得到TLE,分析后觉得是因为加法太慢,所以用贪心法,尽量用乘法。此题类似于求幂值。改用DFS。

解题步骤:

N/A

注意事项:

  1. 若允许乘法次数为0,直接返回加法次数,而不应再用递归,否则会出现超过系统栈深度

Python代码:

1
2
3
4
5
6
7
8
9
def minMoves(self, target: int, maxDoubles: int) -> int:
if target == 1:
return 0
if maxDoubles == 0:
return target - 1
if target % 2 == 0 and maxDoubles > 0:
return self.minMoves(target // 2, maxDoubles - 1) + 1

return self.minMoves(target - 1, maxDoubles) + 1

算法分析:

时间复杂度为O(logn),空间复杂度O(1)


DP算法II解题思路:

TLE

Python代码:

1
2
3
4
5
6
7
8
9
10
# dp[i][j] = dp[i - 1][j], dp[i // 2][j - 1]
def minMoves2(self, target: int, maxDoubles: int) -> int:
dp = [[0] * (maxDoubles + 1) for _ in range(target + 1)]
dp[1][0] = 0
for i in range(2, len(dp)):
for j in range(len(dp[0])):
dp[i][j] = dp[i - 1][j] + 1
if j >= 1 and i % 2 == 0:
dp[i][j] = min(dp[i][j], dp[i // 2][j - 1] + 1)
return dp[-1][-1]

算法分析:

时间复杂度为O(n x maxDoubles),空间复杂度O(n x maxDoubles)

LeetCode

题目大意:

N/A

解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. Python代码:

    1

算法分析:

时间复杂度为O(n),空间复杂度O(1)

LeetCode



Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

The algorithm for myAtoi(string s) is as follows:

1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range [-2<sup>31</sup>, 2<sup>31</sup> - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2<sup>31</sup> should be clamped to -2<sup>31</sup>, and integers greater than 2<sup>31</sup> - 1 should be clamped to 2<sup>31</sup> - 1.
6. Return the integer as the final result.

Note:

Only the space character ' ' is considered a whitespace character. Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example 1:

Input: s = “42”
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: “42” (no characters read because there is no leading whitespace)
^
Step 2: “42” (no characters read because there is neither a ‘-‘ nor ‘+’)
^
Step 3: “42“ (“42” is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.


Example 2:

Input: s = “   -42”
Output: -42
Explanation:
Step 1: “-42” (leading whitespace is read and ignored)
^
Step 2: “ -42” (‘-‘ is read, so the result should be negative)
^
Step 3: “ -42“ (“42” is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.


Example 3:

Input: s = “4193 with words”
Output: 4193
Explanation:
Step 1: “4193 with words” (no characters read because there is no leading whitespace)
^
Step 2: “4193 with words” (no characters read because there is neither a ‘-‘ nor ‘+’)
^
Step 3: “4193 with words” (“4193” is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.


Constraints:

0 <= s.length <= 200 s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.

题目大意:

字符串转整数

解题思路:

关键是第一位是否符号的判断,之后是ord函数的运用

解题步骤:

N/A

注意事项:

  1. 空字符或全空格返回0
  2. [key]若有符号只能第一位是符号,连续是符号不合法返回0,如-+12, 将符号处理放在循环外
  3. 除符号外,若第一位为非数字,不合法,返回0
  4. 循环内,若出现非数字,跳出循环
  5. 计算符号,然后检查数字范围

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def myAtoi(self, s: str) -> int:
s = s.strip()
if not s:
return 0
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
elif s[0] == '+':
s = s[1:]
if s and not s[0].isdigit():
return 0
res = 0
for char in s:
if char.isdigit():
res = res * 10 + ord(char) - ord('0')
else:
break
res *= sign
if res < -pow(2, 31):
return -pow(2, 31)
if res > pow(2, 31) - 1:
return pow(2, 31) - 1
return res

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview