LeetCode 3Sum 解题报告

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

import java.util.*;

public class Solution {

   public List> threeSum(int[] nums) {
     List> result = new ArrayList<>();
     if (nums == null || nums.length < 3) return result;
     Arrays.sort(nums);

     int len = nums.length;
     for (int i = 0; i < len; i++) {
       if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip same results
            int target = 0 - nums[i];
       int j = i + 1, k = len - 1;
       while (j < k) {
         if (nums[j] + nums[k] == target) {
           result.add(Arrays.asList(nums[i], nums[j], nums[k]));
           while (j < k && nums[j] == nums[j + 1]) j++; // Skip same results
                  while (j < k && nums[k] == nums[k - 1]) k--; // Skip same results
                 j++;
          k--;
         } else if (nums[j] + nums[k] < target) {
           j++;
         } else {
            k--;
         }
      }
   }
   return result;
 }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容