当前位置:   article > 正文

leetcode-3SUM(三数相加等于0)_public class findthreesum

public class findthreesum

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

Note:

The solution set must not contain duplicate triplets.

Example:

  1. Given array nums = [-1, 0, 1, 2, -1, -4],
  2. A solution set is:
  3. [
  4. [-1, 0, 1],
  5. [-1, -1, 2]]

Java:

  1. import java.util.Arrays;
  2. import java.util.LinkedList;
  3. import java.util.List;
  4. public class ThreeSum {
  5. public static List<List<Integer>> threeSum(int[] nums) {
  6. //先将数组进行升序排序
  7. Arrays.sort(nums);
  8. LinkedList result = new LinkedList();
  9. //先选择一个数,然后在后面的挑选两个元素求和,因此i < num.length - 2
  10. for(int i = 0; i < nums.length - 2; i++){
  11. //定义两个指针
  12. int lo,hi,sum;
  13. //当i=0时,意味着第一次遍历,当i>0时,若num[i]==num[i-1],则可以跳过该元素(因为数组是有序的)
  14. if(i == 0 || nums[i] != nums[i-1]){
  15. //低位指针从i+1开始,避免重复元祖
  16. lo = i+1;
  17. //高位指针从最后一个元素开始
  18. hi = nums.length-1;
  19. while (lo < hi){
  20. sum = 0 - nums[i];
  21. if(sum == nums[lo]+nums[hi]){
  22. result.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
  23. //若当前指针元素与移动方向上的下一个指针元素相同,则跳过(此处要做++(--)操作才能跳过)
  24. while (lo<hi && nums[lo] == nums[lo+1]) {
  25. lo++;
  26. }
  27. while (lo<hi && nums[hi] == nums[hi-1]) {
  28. hi--;
  29. }
  30. lo++;
  31. hi--;
  32. }
  33. //若两数之和小于0,则lo++;大于0则hi--
  34. else if(nums[lo]+nums[hi] < sum) lo++;
  35. else hi--;
  36. }
  37. }
  38. }
  39. return result;
  40. }
  41. public static void main(String[] args) {
  42. int[] nums= new int[]{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6};
  43. System.out.println(Arrays.deepToString(threeSum(nums).toArray()));
  44. }
  45. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/366061
推荐阅读
相关标签
  

闽ICP备14008679号