博客园markdown太烂, 题解详情https://github.com/TangliziGit/leetcode/blob/master/solution/11-20.md
Leetcode Solution 11~20
marks:
@: hard to get a direct solution
%: need optimization
好题
%%% 11. Container With Most Water[Medium]
%%%%% 15. 3Sum[Medium]
%%% 16. 3Sum Closest [Medium]
% 18. 4Sum [Medium]
总结
- 初始化Stream: Stream.of(), Stream.iterate(0, x->x+1).limit(max)
- map: mapToInt(x -> ...), ...
- filter: filter(x -> ...)
- ending: reduce(Integer::min), findFirst()
- process: getAsInt(), orElse()
- 排序两边夹原理
设z=x+y;
if (z>tar) y<-; else x->;
作用:O(n)二元找x+yz相等(一元找xz相等用二分) - HashSet, HashMap 耗时严重 n次O(1)多花300ms
- 数组排序: Arrays.sort(nums)
- LinkedList方法: add
- 初始化List
: Arrays.asList(X, X, X, ...) - Stack用法: push(), peek(), pop(), isEmpty()
- int[] to List
:
Arrays.sort(arr);
Arrays.stream(arr).boxed().collect(Collectors.toList());
11. Container With Most Water[Medium]
%%% 11. Container With Most Water[Medium]
思路
- O(n^2)
- 树状数组从后向前区间更新最高高度(覆盖),然后从前遍历;再反向计算,取最大值 O(nlogn)
- 二叉搜索树 O(nlogn)
- 双指针,两边夹 O(n)
首先考虑一个解[i,j], 我们需要确定这个范围内解的最大值
在范围减小时, 要使解更大, 唯一的优势就是墙壁高度
所以每次更新时, 贪心的保护最高墙壁
暂时只能这样解释了...
要点
无
代码
class Solution {
public int maxArea(int[] height) {
int l=0, r=height.length-1, ans=0;
while (l<r){
int area=Math.min(height[l], height[r])*(r-l);
ans=Math.max(ans, area);
if (height[l]<height[r]) l++;
else r--;
}return ans;
}
}
12. Integer to Roman[Medium]
12. Integer to Roman[Medium]
思路
水题, 注意题意
要点
无
代码
class Solution {
private static String ans[]=new String[(int)4e3];
private static Integer[] value={
1, 4, 5, 9, 10,
40, 50, 90, 100,
400, 500, 900, 1000};
private static String[] expr={
"I", "IV", "V", "IX", "X",
"XL", "L", "XC", "C",
"CD", "D", "CM", "M"};
public String intToRoman(int num) {
return solve(num, value.length-1);
}
public String solve(int n, int ptr){
if (ptr==-1) return "";
if (ans[n]!=null) return ans[n];
ans[n]=repeat(expr[ptr], n/value[ptr])+
solve(n%value[ptr], ptr-1);
return ans[n];
}
public String repeat(String s, int n){
return new String(new char[n]).replace("