34. Search for a Range
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
思路:二分查找,lower_bound, upper_bound
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lower = self.lowerBound(nums, target)
ans = [-1, -1]
if lower >= 0 and lower < len(nums) and nums[lower] == target:
upper = self.upperBound(nums, target)
ans = [lower, upper-1]
return ans
def lowerBound(self, nums, target):
l, r = 0, len(nums)
while l < r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
else:
r = m
return l
def upperBound(self, nums, target):
l, r = 0, len(nums)
while l < r:
m = (l + r) // 2
if nums[m] <= target:
l = m + 1
else:
r = m
return l
Beat 99.63% python3 2018-06-10
33. Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
思路:二分查找
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums)-1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[l] <= nums[m]:
if nums[l] <= target < nums[m]:
r = m - 1
else:
l = m + 1
else:
if nums[m] < target <= nums[r]:
l = m + 1
else:
r = m - 1
return -1
Beat 98.97% python3 2018-06-11
221. Maximal Square
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
思路:DP
class Solution:
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0:
return 0
rows = len(matrix)
cols = len(matrix[0])
dp = [[0 for i in range(cols+1)] for j in range(rows+1)]
ans = 0
for i in range(1, rows+1):
for j in range(1, cols+1):
if matrix[i-1][j-1] == '1':
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
ans = max(ans, dp[i][j])
return ans*ans
Beat 20.66% python3 2018-06-12
class Solution:
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0:
return 0
rows = len(matrix)
cols = len(matrix[0])
dp = [[0 for i in range(cols+1)] for j in range(rows+1)]
ans = 0
for i in range(1, rows+1):
for j in range(1, cols+1):
if matrix[i-1][j-1] == '1':
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
if dp[i][j] > ans:
ans = dp[i][j]
return ans*ans
Beat 97.52% python3 2018-06-12
15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:选定一个,然后two_sum(两个指针)
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def twoSum(start, target):
l = start
r = length-1
while l < r:
if nums[l] + nums[r] == target:
vl, vr = nums[l], nums[r]
ans.append([-target, vl, vr])
while l < r and nums[l] == vl:
l += 1
while l < r and nums[r] == vr:
r -= 1
elif nums[l] + nums[r] < target:
l += 1
else:
r -= 1
length = len(nums)
if length < 3:
return []
nums.sort()
ans = []
i = 0
while i < length - 2:
twoSum(i+1, -nums[i])
vi = nums[i]
while i < length - 2 and nums[i] == vi:
i += 1
return ans
Beat 29.20% python3 2018-06-13
优化:
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
length = len(nums)
nums.sort()
ans = []
i = 0
for i in range(length-2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i-1]:
continue
l = i+1
r = length-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s == 0:
ans.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l+1]:
l += 1
while l < r and nums[r] == nums[r-1]:
r -= 1
l, r = l+1, r-1
elif s < 0:
l += 1
else:
r -= 1
return ans
Beat 90.56% python3 2018-06-13
思路:或者三个数全0,或者必定有一个整数,一个负数
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
d = {}
for n in nums:
if n in d:
d[n] += 1
else:
d[n] = 1
ans = []
if 0 in d and d[0] > 2:
ans.append([0, 0, 0])
negative = sorted(x for x in d if x < 0)
positive = sorted(x for x in d if x >= 0)
for n in negative:
for p in positive:
s = -(n + p)
if s in d:
if s in (n, p) and d[s] > 1:
ans.append([n, p, s])
elif s < n:
ans.append([n, p, s])
elif p < s:
ans.append([n, p, s])
return ans
Beat 100.00% python3 2018-06-13
152. Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
思路:DP
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp_min = [0] * len(nums)
dp_max = [0] * len(nums)
ans = dp_min[0] = dp_max[0] = nums[0]
for i in range(1, len(nums)):
x, y = dp_max[i-1] * nums[i], dp_min[i-1] * nums[i]
dp_max[i] = max(nums[i], x, y)
dp_min[i] = min(nums[i], x, y)
if ans < dp_max[i]:
ans = dp_max[i]
return ans
Beat 97.39% python3 2018-06-14