You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
(一堆竖线找能装最多水的两条,返回水量)
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
1. Container With Most Water(题目代号11)
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.
(一堆竖线找能装最多水的两条,返回水量)
答:
暴力穷举会超时,看了官方给的答案后真是太妙了,从数组两端开始,每次算一下当前的水量并维护一个最大值,每次让较短的那条线的指针往里移动,直到两条线碰面为止,AC代码如下:
2.3Sum(题目代号15)
Given an array S of n integers, are there elements a, b, c in S 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.
答:
将问题转化一下,其实就是先固定一个数,剩下的就是找两个数,他俩的和为其相反数,这就清晰多了,先把数组排好序,固定的那个数a[i]当然是循环从第一个开始到0结束,因为把负数都找一遍后正数也没必要再找了,找两个和为a[i]的数a[left]和a[right]就一个下标从i+1向后,另一个从len-1向前,如果比a[i]相反数大,说明加多了,要把right减一,否则就把left加一,如果找到相等的,就把三个数推进答案数组,还有最关键的防止TLE的步骤就是如果此时a[left+1]=a[left],就跳过a[left+1],right那侧也一样,循环外部的i也同理,这样可以跳过很多重复的搜索,是AC的关键,代码如下
The text was updated successfully, but these errors were encountered: