15.3Sum

15. 3Sum

题目地址

https://leetcode.com/problems/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]
]

代码

Approach 1: 排序 + 2 Sum

一个For循环 + 双指针 (注意去重)

class Solution {
  public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
      if (i > 0 && nums[i] == nums[i - 1]) {
        continue;
      }
      int left = i + 1;
      int right = nums.length - 1;
      while (left < right) {
        int tmp = nums[left] + nums[right]; // two sum 
        if (tmp + nums[i] == 0) {
          result.add(Arrays.asList(nums[i], nums[left], nums[right]));
          left++;
          // 去重
          while (left < right && nums[left] == nums[left - 1]) {
            left++;
          }
        } else if (tmp + nums[i] < 0) {
          left++;
        } else {
          right--;
        }
      }
    }

    return result;
  }
}

Last updated