LeetCode#15. 3Sum

来源:互联网 发布:四大公司人工智能 编辑:程序博客网 时间:2024/06/10 05:43
  • 题目:给定一个数组,找出所有不重复的三元组,使用三元组的加和为0
  • 难度:Medium
  • 思路:先对数组排序,循环遍历数组,然后每次循环nums[i]定义两个指针,判断指针所指元素相加是否等于-nums[i]
  • 代码:
public class Solution {    public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> result = new ArrayList<>();        if(nums == null || nums.length < 3){            return result;        }        Arrays.sort(nums);        if(nums[0] > 0){            return result;        }        for(int i = 0; i < nums.length; i++){            int sum = 0-nums[i];            int low = i+1;            int high = nums.length-1;            if((i == 0 || (i > 0 && nums[i] != nums[i-1])) && nums[i] <= 0){                while(low < high){                    if(nums[low] + nums[high] == sum){                        result.add(Arrays.asList(nums[i], nums[low], nums[high]));                        while(low < high && nums[low] == nums[++low]);                        while(low < high && nums[high] == nums[--high]);                    }else if(nums[low] + nums[high] > sum){                        high--;                    }else{                        low++;                    }                }            }        }        return result;    }}
原创粉丝点击