Home [Algorithm] 3Sum
Post
Cancel

[Algorithm] 3Sum

‘3Sum’ in LeetCode (Medium)


📌 Problem

https://leetcode.com/problems/3sum/

📌 Answer

The point

  • Sort array first
  • Used Two-pointers technique
    • i and j

More detail about ‘Two pointers algorithm’

Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        Arrays.sort(nums);
        
        List<List<Integer>> list = new ArrayList<>();
    
        for (int i = 0; i < nums.length - 2; i++) {
            
            // avoid duplicates
            if (i > 0 && (nums[i] == nums[i-1])) continue;
            
            // start : i, j , , , , , k
            int j = i + 1;
            int k = nums.length-1;
            
            while (j < k) {

                int sum = nums[i] + nums[j] + nums[k];

                if (sum == 0) {
                    
                    list.add(Arrays.asList(nums[i], nums[j], nums[k]));

                    // move again to make new list
                    j++;
                    k--;

                    // avoid duplicates
                    while ((j < k) && (nums[j] == nums[j - 1])) j++;
                    while ((j < k) && (nums[k] == nums[k + 1])) k--;

                }
                else if (sum > 0) k--;
                else if (sum < 0) j++;
            }
        }

        return list;
    }
}
/**
[Question]
- return all the triplets [nums[i], nums[j], nums[k]]
- condition
    - i != j, i != k, j != k (index)
    - nums[i] + nums[j] + nums[k] == 0 (value)
    - the solution set must not contain duplicate triplets.
**/

The source : https://leetcode.com/problems/3sum/discuss/7631/Simple-Java-Solution-Without-using-HashSet

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Longest Palindromic Substring

[Algorithm] Letter Combinations of a Phone Number

Comments powered by Disqus.