Leetcode 15. 3Sum [medium][java]

本文详细探讨了3Sum问题的解决方法,即在一个整数数组中寻找三个元素a、b、c,使得它们的和等于0。通过使用排序和双指针技术,实现了O(n^2)的时间复杂度和O(n)的空间复杂度,有效避免了重复解的问题。
  1. 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:
在这里插入图片描述

Main Trouble: Time Limit
在这里插入图片描述

Solution
Time Complexity: O(n^2), Space Complexity: O(n)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> triplets = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        
                
        for(int i = 0; i < nums.length-2; i++) {
            // to solve time limit exceed problem
            if(nums[i] > 0)
                break;
            if(i > 0 && nums[i-1] == nums[i])
                continue;
            
            int start = i+1;
            int end = nums.length-1;
            while(start < end) {
                if(nums[i] + nums[start]+nums[end] == 0) {
                    List<Integer> triplet = new ArrayList<Integer>();
                    triplet.add(nums[i]);
                    triplet.add(nums[start]);
                    triplet.add(nums[end]);
                    triplets.add(triplet);
                    start++;
                    end--;
                    // to remove the duplicate
                    while(start < end && nums[start-1] == nums[start]) {
                        start++;
                    }
                    while(start < end && nums[end+1] == nums[end]) {
                        end--;
                    }
                } else if(nums[i] + nums[start]+nums[end] > 0)
                    end--;
                else
                    start++;
            }
        }
        return triplets;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值