LeetCode算法入门- 3Sum -day9

LeetCode算法入门- 3Sum -day9

  1. 题目描述:
    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]
]

  1. 思路分析:
    题目的意思是找到数组中所有3个和为0的数,并且不能重复。

该题可以转化成Two Sum的思路去解决先固定一个数,然后从数组中剩下的数中查找和为该数负值(target)得2个数,则转化成了Two Sum问题:1. 先排序数组,使两个指针分别指向首尾的两个数,2. 如果这两个数和等于target,则找到,3. 如果小于target则右移左指针,如果大于target则左移右指针。

  1. 关键是题目要求去重,所以每次移动指针的时候要判断一下是否和上一个数相同,如果相同则继续移动。
    代码如下:
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int len = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        //记得先排序,这样才能够排除重复的答案
        Arrays.sort(nums);
        for(int i = 0; i < len; i++){
            //这里的i != 0的判断目的是为了i-1不越界
            if(i != 0 && nums[i] == nums[i - 1])
                //continue语法很少用,若条件满足,则不执行当次循环的代码,i要继续+1
                continue;
            int target = -nums[i];
            int left = i + 1;
            int right = len - 1;
            while(left < right){
                if(nums[left] + nums[right] == target){
                    //Arrays.asList()这个方法是直接将元素添加到temp中去
                    List<Integer> temp = Arrays.asList(nums[i],nums[left],nums[right]);
                    result.add(temp);
                    left++;
                    right--;
                    //去重同时记得判断left<right
                    while(left < right && nums[left] == nums[left-1])
                        left++;
                    while(left < right && nums[right] == nums[right+1])
                        right--;
                }
                else if(nums[left] + nums[right] < target){
                    left++;
                }
                else{
                    right--;
                }
            }
            
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值