Leetcode 3Sum 以及相关的题目

15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

先对其排序,外层是一个数,内层其实就是两个数的sum, 然后通过双指针前后来判断,代码如下:

// Time O(n^2)
// Space O(n);
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        //corner case;
        if(nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums); // notice, firstly need sort;
        for(int i = 0; i < nums.length - 2; i++) {  // i < nums.length - 2;
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            int low = i + 1, high = nums.length - 1, sum = 0 - nums[i];
            while(low < high) {
                if(nums[low] + nums[high] == sum) {
                    res.add(Arrays.asList(nums[low], nums[high], nums[i]));
                    while(low < high && nums[low] == nums[low + 1]) low++; // notice this place is "low + 1";
                    while(low < high && nums[high] == nums[high - 1]) high--;
                    low++;
                    high--;
                }else if(nums[low] + nums[high] < sum) {
                    low++;
                }else {
                    high--;
                }
            }
            
        }
        return res;
    }
}

16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
//Java solution 
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //Arrays.sort()是O(nlogn)的,只要是基于比较的排序算法都是不低于nlogn的
        Arrays.sort(nums);
        int closest = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.length; i++) {
            int low = i + 1, high = nums.length - 1;
            while(low < high) {
                int newClosest = nums[i] + nums[low] + nums[high];
                int remain = target - newClosest;
                if(remain > 0) {
                    low++;
                }else if(remain < 0) {
                    high--;
                }else {
                    return target;
                }
                closest = Math.abs(target - closest) < Math.abs(target - newClosest) ? closest : newClosest;
            }
        }
        return closest;
    }
}

259. 3Sum Smaller

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

Example:

Input: nums = [-2,0,1,3], and target = 2
Output: 2 
Explanation: Because there are two triplets which sums are less than 2:
             [-2,0,1]
             [-2,0,3]

Follow up: Could you solve it in O(n2) runtime?
思路:
Let us try sorting the array first. For example, nums = [3,5,2,8,1] becomes[1,2,3,5,8].
Let us look at an example nums=[1,2,3,5,8], and target = 7.

[1, 2, 3, 5, 8]
 ↑           ↑
left       right

Let us initialize two indices, left and right pointing to the first and last element respectively.
When we look at the sum of first and last element, it is 1 + 8 = 9, which is ≥ target. That tells us no index pair will ever contain the index right. So the next logical step is to move the right pointer one step to its left.

[1, 2, 3, 5, 8]
 ↑        ↑
left    right

Now the pair sum is 1+5=6, which is < target. How many pairs with one of the index = left that satisfy the condition? You can tell by the difference between right and left which is 3, namely (1,2), (1,3), and (1,5). Therefore, we move left one step to its right.

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int sum = 0;
        for(int i = 0; i < nums.length - 2; i++) {
            sum += twoSumSmaller(nums, i + 1, target- nums[i]);
        }
        return sum;
    }
    public int twoSumSmaller(int[] nums, int startIndex, int target) {
        int low = startIndex;
        int high = nums.length - 1;
        int sum = 0;
        while(low < high) {
            if(nums[low] + nums[high] < target) {
                sum += high - low;
                low++;
            }else {
                high--;
            }
        }
        return sum;
    }
}

参考文献: https://leetcode.com/problems/3sum-smaller/solution/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,732评论 6 539
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,214评论 3 426
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 177,781评论 0 382
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,588评论 1 316
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,315评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,699评论 1 327
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,698评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,882评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,441评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,189评论 3 356
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,388评论 1 372
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,933评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,613评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,023评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,310评论 1 293
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,112评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,334评论 2 377

推荐阅读更多精彩内容