首页 > 其他 > 详细

三数之和

时间:2020-06-14 23:02:01      阅读:52      评论:0      收藏:0      [点我收藏+]

1:题目描述

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

 

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2:题目分析

  首先,这是数字之和的问题,杂乱无章的数据显然不利于我们进行处理,所有首先想到进行排序处理,我们可以利于Arrays.sort方法进行排序,然后在进行针对之和为0的处理,显然这里就可以通过一一比较的到,因为排序后的数据之间大小关系明确,如果此时的三数之和较大,则只需要想左移,如果较小则进行右移即可。而针对重复项,这可以通过相邻数是不是相等来排除重复项。

3:代码示例

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeNumSum {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();

        int len = nums.length;
        //handle boundary conditions
        if(nums==null||len<3) {
            return ans;
        }
        //sort this array first
        Arrays.sort(nums);

        for(int i=0;i<len;i++){
            if(nums[i]>0) break;//if nums[i] is greater than 0, three nums sum must be greater than 0  too.
            if(i>0&&nums[i]==nums[i-1]) continue;//if this two near numbers are same value,that means wo have to skip one of those two numbers to avoid get same result.
            int L =i + 1;
            int R =len - 1;

            while(L < R){
                int sum = nums[i]+nums[L]+nums[R];
                if(sum == 0){
                    ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while(L<R&&nums[L]==nums[L+1]) L++;//skip the same result
                    while(L<R&&nums[R]==nums[R-1]) R--;//skip the same result
                    L++;
                    R--;
                }
                else{
                    if(sum<0) L++;
                    else R--;
                }
            }
        }
        return ans;
    }
}

 

三数之和

原文:https://www.cnblogs.com/dazhu123/p/13127335.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!