三数之和

  1. 问题描述

      leetcode 15,找出给定数组中的满足和为目标值的所有不重复组合
  2.  解决思路

      先对数组排序,再设置两个头尾指针,和一个顺序指针,共三个指针。头尾指针在最外层指针下进行查找。
  3. 注意事项

      注意去除重复情况。
     1 public class Solution {
     2     public static List<List<Integer>> threeSum(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         Arrays.sort(nums);
     5         int length = nums.length;
     6         for(int i=0; i<length-2; i++){
     7             // 最外层的去重方法
     8             if(i>0 && nums[i]==nums[i-1]) {
     9                 continue;
    10             }
    11             int leftP = i+1;
    12             int rightP = length-1;
    13             while(leftP<rightP) {
    14                 int temp = nums[i] + nums[leftP] + nums[rightP];
    15                 if (temp<0) {
    16                     leftP += 1;
    17                 } else if (temp >0) {
    18                     rightP -= 1;
    19                 } else {
    20                     res.add(Arrays.asList(nums[i], nums[leftP], nums[rightP]));
    21                     // 内层的左指针去重方法,注意是一直到不重复,所以用while
    22                     while (leftP < rightP && nums[leftP]==nums[leftP+1]) {
    23                         leftP += 1;
    24                     }
    25                     // 内层的右指针去重
    26                     while (leftP < rightP && nums[rightP]==nums[rightP-1]) {
    27                         rightP -= 1;
    28                     }
    29                     leftP += 1;
    30                     rightP -= 1;
    31                 }
    32             }
    33         }
    34 
    35         return  res;
    36     }
    37 }

     

posted @ 2019-05-29 22:10  LimLee  阅读(127)  评论(0编辑  收藏  举报