15. 3Sum (JAVA)

Given an array nums of n integers, are there elements abcin nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.數組

Note:ide

The solution set must not contain duplicate triplets.spa

Example:指針

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

 

class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ret = new ArrayList<>() ; if(nums.length==0) return ret; int target; int len = nums.length-2; int left; //point to the left side of the array
        int right; //point to the right side of the array
 Arrays.sort(nums); for(int i = 0; i < len; i++){ target = 0 - nums[i]; left = i+1; right = len+1; if(nums[left] > target) break; while(left < right){ if(nums[left] + nums[right] > target){ right--; } else if(nums[left] + nums[right] < target){ left++; } else{ List<Integer> ans = new ArrayList<>(); ans.add(nums[i]); ans.add(nums[left]); ans.add(nums[right]); ret.add(ans); //to avoid IndexOutOfBoundsException
                    left++; right--; //for uniqueness
                    while(nums[left] == nums[left-1] && left < right) left++; while(nums[right] == nums[right+1] && left < right) right--; } } while(nums[i] == nums[i+1]) { if(i+1 < len) i++; //for uniqueness
                else return ret; } } return ret; } }

數組問題注意:下標越界code

時間複雜度:O(n2),經過兩個指針向中間夾逼的方法使得兩個數求和的時間複雜度從O(n2)->O(n)。blog

相關文章
相關標籤/搜索