【leetcode刷题笔记】3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)


题解:把3Sum转换成2Sum,然后解决2Sum问题。

对于num中任意一个数num[i],我们要在i+1~num.length-1之间寻找两个数使得它们的和为0-num[i]。

而寻找两个数使得它们的和为0-num[i],我们可以设定两个指针start和last,我们知道在start+1~last之间我们要寻找的数是0-num[i]-num[start],这样三个数的和就是0了。所以如果

  • last所指向的数比0-num[i]-num[start]大,我们把last指针往前移动;
  • 如果比0-num[i]-num[start]小,我们把start指针往后移动(last指针不动是因为我们已经搜索过了可能和last指针后面组成答案的数,这些数在start之前);
  • 如果相等,就把num[i],num[start]和num[last]三个数依次放在list中作为一组答案。然后越过start后面和start相等的数,继续循环。

图示如下:

例如题目的数组排序后得到{-4,-1,0,1,2},当i指向-1的时候,我们需要在{0,1,2}之中找到两个数和为0-(-1)=1,把start指向0,last指向2,那么我们接下来要利用last找到1,last目前指向2,比需要的数1大,所以前移last,wala,我们找到了需要的1,同时找到了一组答案[-1,0,1]。

去重的工作十分简单,除了上述说的越过start后面和start相等的数外,在最外层的for循环的时候,如果num[i] = num[i-1],那么也可以越过i。

最后代码如下:

 1 public class Solution {
 2     public List<List<Integer>> threeSum(int[] num) {
 3         List<List<Integer>> answer = new ArrayList<List<Integer>>();
 4         if(num == null || num.length == 0)
 5             return answer;
 6         Arrays.sort(num);
 7
 8         for(int i = 0;i < num.length;i++){
 9         //remove duplicates
10             if(i != 0 && num[i] == num[i-1])
11                 continue;
12             int twoSum = 0 - num[i];
13             int start = i + 1;
14             int last = num.length-1;
15             while(start < last){
16                 int OneSum = twoSum - num[start];
17          //Found one solution
18                 if(num[last] == OneSum){
19                     ArrayList<Integer> result = new ArrayList<Integer>();
20                     result.add(num[i]);
21                     result.add(num[start]);
22                     result.add(num[last]);
23                     answer.add(result);
24                     start++;
25                     last--;
26             //remove duplicates
27                     while(start < last && num[start] == num[start-1])
28                         start++;
29                 }
30                 else if(num[last] > OneSum)
31                 {
32                     last--;
33                 }
34                 else{
35                     start++;
36                 }
37             }
38         }
39
40         return answer;
41     }
42 }

【leetcode刷题笔记】3Sum

时间: 2024-10-02 18:02:31

【leetcode刷题笔记】3Sum的相关文章

【leetcode刷题笔记】4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order.

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的