1. 程式人生 > >leetcode two pointer

leetcode two pointer

我們 .cn support length i+1 post pub ret and

16. 3Sum Closest

這道題讓我們求最接近給定值的三數之和,是在之前那道 3Sum 三數之和的基礎上又增加了些許難度,那麽這道題讓我們返回這個最接近於給定值的值,即我們要保證當前三數和跟給定值之間的差的絕對值最小,所以我們需要定義一個變量result用來記錄當前最小三個數的和,然後我們還是要先將數組排個序,然後開始遍歷數組,思路跟那道三數之和很相似,都是先確定一個數,然後用兩個指針left和right來滑動尋找另外兩個數,每確定兩個數,我們求出此三數之和sum,然後算和給定值的差的絕對值abs(sum-target),然後和abs(result-target)比較並更新結果result即可,代碼如下:

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        int result = num[0] + num[1] + num[num.length - 1];//初始化
        Arrays.sort(num);
        //選擇一個數
        for (int i = 0; i < num.length - 2; i++) {
            int start = i + 1, end = num.length - 1;//雙指針指向最小數和最大數
while (start < end) { int sum = num[i] + num[start] + num[end]; if (sum > target) { //大了,後一個指針前移 end--; } else { //小了,前一個指針後移 start++; } if (Math.abs(sum - target) < Math.abs(result - target)) { result
= sum; } } } return result; } }

15. 3Sum

這道題讓我們求三數之和,返回符合條件的集合

和上面一樣,除了需要跳過相同的數字避免集合出現重復

public List<List<Integer>> threeSum(int[] num) {
    Arrays.sort(num);
    List<List<Integer>> res = new LinkedList<>(); 
    for (int i = 0; i < num.length-2; i++) {
        if (i == 0 || (i > 0 && num[i] != num[i-1])) {
            int lo = i+1, hi = num.length-1, sum = 0 - num[i];
            while (lo < hi) {
                if (num[lo] + num[hi] == sum) {
                    res.add(Arrays.asList(num[i], num[lo], num[hi]));
                    while (lo < hi && num[lo] == num[lo+1]) lo++;//skip
                    while (lo < hi && num[hi] == num[hi-1]) hi--;//skip
                    lo++; hi--;
                } else if (num[lo] + num[hi] < sum) lo++;
                else hi--;
           }
        }
    }
    return res;
}

使用工具類Arrays.asList()把數組轉換成集合時,不能使用其修改集合相關的方法,它的add/remove/clear方法會拋出UnsupportOperationException異常
說明:asList的返回對象是一個Arrays內部類,並沒有實現集合的修改方法。Arrays.asList體現的是適配器模式,只是轉換接口,後臺的數據仍是數組。
String[] str = new String[]{"1","2"};
List list = Arrays.asList(str);
第一種情況:list.add("x");//運行時異常
第二種情況:str[0] = "unv";//那麽list.get(0)也隨著修改。

leetcode two pointer