LeetCode选题:
11. Container With Most Water
题目:
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
我的解法(思路):
容积取决于两根线之间的距离,以及较短那根线的长度。从左到右遍历所有的线,并且找到比它长或等于它的、离它最远的那根线,计算面积。然后取得到面积最大的那两根线。
例如,当遍历到中间的某根线的时候,先从它的最左边(第一个)遍历到它,找到第一个长度大于等于它的线,计算面积;再从它的最右边(最后一个)遍历到它,找到第一个长度大于等于它的线,计算面积。取两者的最大值,即该线作为较短线所能得到的最大面积。
缺点:
时间复杂度接近O(n^2 )
代码:
class Solution:
def maxArea(self, height):
Max = 0
for i in range(len(height)):
if len(height) == 2:
Max = min(height[0], height[1])
else:
for a in range(i):
if i == 0:
break
if height[a] >= height[i]:
Max = max( (i-a)*height[i], Max)
break
for b in range(1, len(height)-i):
if i == len(height)-1:
break
if height[-b] >= height[i]:
Max = max( (len(height)-b-i)*height[i], Max)
break
return Max
测试:
能过一些基础样例,但较大的样例无法通过,如
[1, 2, 3, 4,…..,2998, 2999, 3000]
更优解法:
(参考自https://leetcode.com/problems/container-with-most-water/solution/)
class Solution:
def maxArea(self, height):
maxarea = 0
l, r = 0, len(height)-1
while (l < r):
maxarea = max(maxarea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxarea
思路:
选择的两条线从两边向中间收缩,底边(两线距离)越来越小,高度(较短那根线)越来越大。时间复杂度O(n)。
核心思想:得到一条线与距离它最远的那条大于等于它的线所得到的面积。
2. Add Two Numbers
题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
我的解法(思路):
将输入的两列表相应的位直接相加,并放在一个列表的对应的位中,例如:
[2, 4, 3] + [5, 6, 4] = [7, 10, 7]
然后,将对应的位乘以它的权值,再相加,即可得到一个整数值,即
7 * 1 + 10 * 10 + 7 * 100 = 807
最后,用取模运算,将其放入一个列表中。
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = []
while l1 and l2:
temp.append(l1.val + l2.val)
l1 = l1.next
l2 = l2.next
l3 = l1 if l1 else l2
while l3:
temp.append(l3.val)
l3 = l3.next
sum = 0
for i in range(len(temp)):
sum += temp[i] * (10 ** i)
#print(sum)
res = ListNode(sum%10)
res_temp = res
sum = sum // 10
while sum:
res_temp.next = ListNode(sum%10)
res_temp = res_temp.next
sum = sum // 10
return res