每日leetcode4.12-盛水(双指针)+最大数(排序)
11. 盛最多水的容器
典型双指针
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
ans = 0
while i < j:
v = 0
if height[i] < height[j]:
v = height[i] * (j - i)
i += 1
else:
v = height[j] * (j - i)
j -= 1
if v > ans:
ans = v
return ans
if __name__ == '__main__':
x = Solution()
s = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(x.maxArea(s))
179. 最大数
注意处理0的情况,其次py中排序方法是利用关键字的大小,py3中不再有cmp
from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
if sum(nums) == 0:
return "0"
def cmp(x):
if x == 0:
return 0
v = []
l = 0
while x:
v.append(x % 10)
x //= 10
l += 1
ans = 0
for i in range(9):
ans = ans * 10 + v[l - 1 - i % l]
return ans
ans = ""
nums.sort(key=cmp, reverse=True)
for i in nums:
ans += str(i)
return ans
if __name__ == '__main__':
x = Solution()
s = [0]
print(x.largestNumber(s))