[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]

鎬荤粨

  1. 鍒濆鍖朣tream: Stream.of(), Stream.iterate(0, x->x+1).limit(max)
  2. map: mapToInt(x -> ...), ...
  3. filter: filter(x -> ...)
  4. ending: reduce(Integer::min), findFirst()
  5. process: getAsInt(), orElse()
  6. 鎺掑簭涓よ竟澶瑰師鐞?/strong>
    璁緕=x+y;
    if (z>tar) y<-; else x->;
    浣滅敤锛歄(n)浜屽厓鎵緓+y==z鐩哥瓑锛堜竴鍏冩壘x==z鐩哥瓑鐢ㄤ簩鍒嗭級
  7. HashSet, HashMap 鑰楁椂涓ラ噸 n娆(1)澶氳姳300ms
  8. 鏁扮粍鎺掑簭: Arrays.sort(nums)
  9. LinkedList鏂规硶: add
  10. 鍒濆鍖朙ist: Arrays.asList(X, X, X, ...)
  11. Stack鐢ㄦ硶: push(), peek(), pop(), isEmpty()
  12. 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]

鎬濊矾

  1. O(n^2)
  2. 鏍戠姸鏁扮粍浠庡悗鍚戝墠鍖洪棿鏇存柊鏈€楂橀珮搴︼紙瑕嗙洊锛夛紝鐒跺悗浠庡墠閬嶅巻锛涘啀鍙嶅悜璁$畻锛屽彇鏈€澶у€?O(nlogn)
  3. 浜屽弶鎼滅储鏍?O(nlogn)
  4. 鍙屾寚閽?涓よ竟澶?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

瑕佺偣

  1. 鍒濆鍖朣tream: Stream.of(), Stream.iterate(0, x->x+1).limit(max)
  2. map: mapToInt(x -> ...), ...
  3. filter: filter(x -> ...)
  4. ending: reduce(Integer::min), findFirst()
  5. 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-nums[i]) r--; else l++; } } return ans; } } ``` O(n^2+nlogn+n) with a small constant ```java class Solution{ public List> threeSum(int[] nums) { Map map=new HashMap(); Set> set=new HashSet(); LinkedList> ans=new LinkedList(); Arrays.sort(nums); // if duplicated, use the last one for (int i=0; i> threeSum(int[] nums) { Map> map=new HashMap(); Set> set=new HashSet(); ArrayList> ans=new ArrayList(); Arrays.sort(nums); for (int i=0; i()); // O(1) List list=map.get(sum); // O(1) list.add(new Pair(i, j)); // O(1)? } } for (int i=0; ipair.y && i!=pair.x && i!=pair.y){ set.add(Arrays.asList(nums[pair.x], nums[pair.y], nums[i])); } } for (List list: set) ans.add(list); return ans; } static class Pair{ final int x, y; Pair(int x, int y){ this.x=x; this.y=y; } } } ```

16. 3Sum Closest [Medium]

%%% 16. 3Sum Closest [Medium]

鎬濊矾

  1. O(n^3)
  2. O(n^2logn) 浜屽垎
  3. O(n^2) 鍙屾寚閽? 涓よ竟澶规眰鏈€杩? 鍥犱负杩欎笁閬撻閮芥槸鍙屾寚閽? 鎵€浠ユ湁鐐逛細鐢ㄤ簡

瑕佺偣

  1. 鏁扮粍鎺掑簭: 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]

鎬濊矾

姘撮, 閫掑綊

瑕佺偣

  1. LinkedList鏂规硶: add
  2. 鍒濆鍖朙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: ```java Arrays.sort(arr); Arrays.stream(arr).boxed().collect(Collectors.toList()); ``` ### 浠g爜 ```java class Solution { public 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> map=new HashMap(); Set> set=new HashSet(); LinkedList> ans=new LinkedList(); for (int i=0; i list: set) ans.add(list); return ans; } } ```

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>

瑕佺偣

  1. 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的主要内容,如果未能解决你的问题,请参考以下文章

璁板綍瑙嗛鈥?Why I build Docker"

淇濇姢鍔熻兘璁板綍

Oracle寤鸿〃鑴氭湰璁板綍

Github浣跨敤璁板綍

JAVA鍏ラ棬濉潙璁板綍

璁板綍 瀹岀編瑙g爜 閰嶇疆