Leetcode || 3Sum

来源:互联网 发布:淘宝1元秒杀怎么抢 编辑:程序博客网 时间:2024/06/08 01:25

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.

package pack;import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;/* * 求三数和为0,遍历一个数,以它为定点,再转化为2Sum */class Solution {    public List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        HashSet hs = new HashSet(); //最后不会有重复        for(int i=0; i<nums.length; i++) {            int left = i + 1;  //最关键的地方,如果是想办法去掉定点后left=0,会重复计算            int right = nums.length-1;            while(left < right) {                if(nums[left] + nums[right] > -nums[i]) {                    right--;                }                else if(nums[left] + nums[right] < -nums[i]) {                    left++;                }                else {                    List li = new ArrayList();                    li.add(nums[i]);                    li.add(nums[left]);                    li.add(nums[right]);                    hs.add(li);                    //break;   //以每个为定点,答案可能有多个                    left++;                        right--;                }            }        }        return new ArrayList(hs);    }}public class Main {    public static void main(String[] args) {        int[] arr = new int[] {-2,0,1,1,2};        System.out.println(new Solution().threeSum(arr));    }}
0 0
原创粉丝点击