[LeetCode]18. 4Sum java

    xiaoxiao2021-03-25  120

    /**18. 4Sum * @param nums * @param target * @return 4个数之和为target */ public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<List<Integer>>(); HashSet<List<Integer>> set = new HashSet<List<Integer>>(); Arrays.sort(nums); for (int i=0, len=nums.length; i<len-4; i++) { for (int j=i+1; j<len-3; j++) { int low = j+1; int high = len-1; while (low < high) { int sum = nums[i] + nums[j] + nums[low] + nums[high]; if (sum == target) { List<Integer> item = new ArrayList<Integer>(); item.add(nums[i]); item.add(nums[j]); item.add(nums[low]); item.add(nums[high]); if (!set.contains(item)) { set.add(item); list.add(item); } low++; high--; } else if(sum < target) { low++; } else { high--; } } } } return list; }

    注意:找到item之后更改指针位置哦

    转载请注明原文地址: https://ju.6miu.com/read-4869.html

    最新回复(0)