[leetcode] 棰樿В璁板綍 11-20
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 棰樿В璁板綍 11-20相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/ali' title='ali'>ali
tps abs hash ace string tor array http鍗氬鍥璵arkdown澶儌, 棰樿В璇︽儏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]
鎬荤粨
- 鍒濆鍖朣tream: Stream.of(), Stream.iterate(0, x->x+1).limit(max)
- map: mapToInt(x -> ...), ...
- filter: filter(x -> ...)
- ending: reduce(Integer::min), findFirst()
- process: getAsInt(), orElse()
- 鎺掑簭涓よ竟澶瑰師鐞?/strong>
璁緕=x+y;
if (z>tar) y<-; else x->;
浣滅敤锛歄(n)浜屽厓鎵緓+y==z鐩哥瓑锛堜竴鍏冩壘x==z鐩哥瓑鐢ㄤ簩鍒嗭級
- HashSet, HashMap 鑰楁椂涓ラ噸 n娆(1)澶氳姳300ms
- 鏁扮粍鎺掑簭: Arrays.sort(nums)
- LinkedList鏂规硶: add
- 鍒濆鍖朙ist
: 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], 鎴戜滑闇€瑕佺‘瀹氳繖涓寖鍥村唴瑙g殑鏈€澶у€?br /> 鍦ㄨ寖鍥村噺灏忔椂, 瑕佷娇瑙f洿澶? 鍞竴鐨勪紭鍔垮氨鏄澹侀珮搴?br /> 鎵€浠ユ瘡娆℃洿鏂版椂, 璐績鐨勪繚鎶ゆ渶楂樺澹?br /> 鏆傛椂鍙兘杩欐牱瑙i噴浜?..
瑕佺偣
鏃?/p>
浠g爜
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] ### 鎬濊矾 姘撮, 娉ㄦ剰棰樻剰 ### 瑕佺偣 鏃? ### 浠g爜 ```java 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(" ", s); } } ```13. Roman to Integer [Easy]
13. Roman to Integer [Easy]
鎬濊矾
姘撮, 娉ㄦ剰棰樻剰
瑕佺偣
鏃?/p>
浠g爜
class Solution {
private static Map<Character, Integer> map=new HashMap();
static{
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
};
public int romanToInt(String s) {
int ans=0, len=s.length();
for (int i=0; i<len; i++)
if (i+1<len && map.get(s.charAt(i))<map.get(s.charAt(i+1)))
ans-=map.get(s.charAt(i));
else
ans+=map.get(s.charAt(i));
return ans;
}
}
14. Longest Common Prefix [Easy]
14. Longest Common Prefix [Easy]
鎬濊矾
姘撮
鍒氬ソ鐢ㄦ潵鍐橲tream
瑕佺偣
- 鍒濆鍖朣tream: Stream.of(), Stream.iterate(0, x->x+1).limit(max)
- map: mapToInt(x -> ...), ...
- filter: filter(x -> ...)
- ending: reduce(Integer::min), findFirst()
- process: getAsInt(), orElse()
浠g爜
// Stream version
// 47ms, 38MB
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs==null || strs.length==0) return "";
int minlen=Stream.of(strs)
.mapToInt(x -> x.length())
.reduce(Integer::min)
.getAsInt();
int idx=Stream.iterate(0, x -> x+1).limit(0+minlen)
.filter(x -> check(strs, x))
.findFirst()
.orElse(minlen);
return strs[0].substring(0, idx);
}
public boolean check(String[] strs, int idx){
return Stream.of(strs)
.anyMatch(x -> x.charAt(idx)!=strs[0].charAt(idx));
}
}
// Original
// 4ms, 39MB
class OriginalSolution {
public String longestCommonPrefix(String[] strs) {
if (strs==null || strs.length==0) return "";
int idx=0, minlen=strs[0].length();
for (String str: strs)
minlen=Math.min(minlen, str.length());
for (;idx<minlen; idx++)
if (check(strs, idx)) break;
return strs[0].substring(0, idx);
}
public boolean check(String[] strs, int idx){
for (String str: strs)
if (str.charAt(idx)!=strs[0].charAt(idx))
return true;
return false;
}
}
15. 3Sum[Medium]
## %%%%% 15. 3Sum[Medium] ### 鎬濊矾 1. O(n^3) 2. O(n^2logn): for^2 + binarySearch 3. O(n^2+nlogn+n) with a big constant: 鍙栧緱涓ら」鍜岀殑map锛岀劧鍚庨亶鍘嗭紝鏈€鍚庡幓閲? 4. O(n^2+nlogn+2n) with a small constant: 鎺掑簭锛屽緱涓€涓厓绱犵殑瀵瑰簲涓嬫爣map锛岃嫢閲嶅鍙栨渶鍚? for^2 鏌ユ壘锛屾彃鍏ashSet 5. O(n^2) with a smaller constant: for x: 涓よ竟澶规壘y+z==-x ### 瑕佺偣 1. **鎺掑簭涓よ竟澶瑰師鐞?* 璁緕=x+y; if (z>tar) y<-; else x->; 浣滅敤锛歄(n)浜屽厓鎵緓+y==z鐩哥瓑锛堜竴鍏冩壘x==z鐩哥瓑鐢ㄤ簩鍒嗭級 2. HashSet, HashMap 鑰楁椂涓ラ噸 n娆(1)澶氳姳300ms ### 浠g爜 O(n^3) version ```java class Solution{ public List- > threeSum(int[] nums) {
LinkedList
- > ans=new LinkedList();
Arrays.sort(nums);
for (int i=0; i
- > threeSum(int[] nums) {
Map
- > set=new HashSet();
LinkedList
- > ans=new LinkedList();
Arrays.sort(nums);
// if duplicated, use the last one
for (int i=0; i
- > set=new HashSet();
ArrayList
- > ans=new ArrayList();
Arrays.sort(nums);
for (int i=0; i
16. 3Sum Closest [Medium]
%%% 16. 3Sum Closest [Medium]
鎬濊矾
- O(n^3)
- O(n^2logn) 浜屽垎
- O(n^2) 鍙屾寚閽? 涓よ竟澶规眰鏈€杩? 鍥犱负杩欎笁閬撻閮芥槸鍙屾寚閽? 鎵€浠ユ湁鐐逛細鐢ㄤ簡
瑕佺偣
- 鏁扮粍鎺掑簭: Arrays.sort(nums)
浠g爜
class Solution {
public int threeSumClosest(int[] nums, int target) {
int ans=nums[0]+nums[1]+nums[2];
Arrays.sort(nums);
for (int i=0; i<nums.length; i++){
int l=i+1, r=nums.length-1;
while (l<r){
int sum=nums[i]+nums[l]+nums[r];
if (Math.abs(sum-target)<Math.abs(ans-target))
ans=sum;
if (sum<target) l++;
else r--;
}
}return ans;
}
}
17. Letter Combinations of a Phone Number [Medium]
17. Letter Combinations of a Phone Number [Medium]
鎬濊矾
姘撮, 閫掑綊
瑕佺偣
- LinkedList鏂规硶: add
- 鍒濆鍖朙ist
: Arrays.asList(X, X, X, ...)
浠g爜
class Solution {
private String template="abcdefghijklmnopqrstuvwxyz";
public List<String> letterCombinations(String digits) {
if (digits.equals("")) return new ArrayList<String>();
return solve(digits, 0);
}
private List<String> solve(String digits, int ptr){
if (ptr==digits.length()) return Arrays.asList("");
List<String> tmp=solve(digits, ptr+1), ans=new LinkedList();
int num=digits.charAt(ptr)-'2', n=(num+2==9||num+2==7)?4:3;
int offset=(num+2==9||num+2==8)?1:0;
for (String str: tmp){
for (int i=offset; i<n+offset; i++)
ans.add(template.charAt(i+num*3)+str);
}return ans;
}
}
18. 4Sum [Medium]
## % 18. 4Sum [Medium] ### 鎬濊矾 1. O(n^2+nlogn) with big constant: map+set 2. O(n^3) with optimization: for^2 鍙屾寚閽? 涓よ竟澶? 涓昏鑰冭檻涓€涓嬪弻鎸囬拡瑙f硶 ### 瑕佺偣 1. int[] to List- > fourSum(int[] nums, int target) {
int n=nums.length, size=0;
int[] pre=new int[n*(n-1)/2];
int[] pos=new int[n*(n-1)/2];
Map
- > set=new HashSet();
LinkedList
- > ans=new LinkedList();
for (int i=0; i
19. Remove Nth Node From End of List [Medium]
19. Remove Nth Node From End of List [Medium]
鎬濊矾
姘撮
浼樺寲:
鍙互鍦ㄧ涓€涓寚閽堣蛋浜唍涓厓绱犲悗, 鍦ㄨ捣涓€涓寚閽? 绛夌涓€涓粨鏉熶簡涔嬪悗, 鍒犻櫎鍚庝竴涓寚閽堢殑鍏冪礌.
鐒惰€屽澶嶆潅搴︽病鏈夋彁鍗? 鑰屼笖鏈変汉璇磋繖鏄釜寰堝ソ鐨勪紭鍖? 鎴戣绠€鐩存壇娣″ソ鍚?/p>
瑕佺偣
鏃?/p>
浠g爜
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len=0;
ListNode tmp=head;
while (tmp!=null){
len++;
tmp=tmp.next;
}
if (n==len) return head.next;
tmp=head;
for (int i=0; i<len-n-1; i++)
tmp=tmp.next;
tmp.next=tmp.next.next;
return head;
}
}
20. Valid Parentheses [Easy]
20. Valid Parentheses [Easy]
鎬濊矾
姘撮, 鏍?/p>
瑕佺偣
- Stack鐢ㄦ硶: push(), peek(), pop(), isEmpty()
浠g爜
class Solution {
private static Map<Character, Character> map=new HashMap();
static{
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
}
public boolean isValid(String s) {
Stack<Character> sta=new Stack();
int len=s.length();
for (int i=0; i<len; i++){
if (map.containsKey(s.charAt(i))) sta.push(s.charAt(i));
else{
if (!sta.isEmpty() && s.charAt(i)==map.get(sta.peek())) sta.pop();
else return false;
}
}
if (sta.isEmpty())
return true;
return false;
}
}
以上是关于[leetcode] 棰樿В璁板綍 11-20的主要内容,如果未能解决你的问题,请参考以下文章