15.三数之和
有点把问题拆分的意思,先固定第一个数,剩下两个双指针找符合条件的数,注意去重条件,为去重最简单高效的办法就是先对数组进行排序,再在判断过程中加上判断i和i-1是否相等。
双指针找条件时,由于数组有序,若结果大于0则让右指针左移,直到左移到小于零再让左指针右移(左右谁先动无所谓)
是一个比较需要思考细节的题
class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> res= new ArrayList<List<Integer>>();Arrays.sort(nums);for(int i=0;i<nums.length;i++){if(i>0&&nums[i]==nums[i-1]) continue;int left=i+1; int right=nums.length-1;while(left<right){if(nums[i]+nums[left]+nums[right]==0){List<Integer> ans= new ArrayList<>();ans.add(nums[i]);ans.add(nums[left]);ans.add(nums[right]);res.add(ans);left++;while(left<right&&nums[left]==nums[left-1]) left++;}else if(nums[i]+nums[left]+nums[right]<0){left++;}else{right--;} }}return res;}
}