java 15. 3Sum(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 15. 3Sum(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
	public List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int len =  nums.length;
        int minNum;
        
        for (int i = 0; i < len - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int a, b, c;
            
            a = nums[i];
            if (a > 0)
                return result;
            
            int low = i + 1, high = len - 1;
            minNum = -a - nums[high];
			while(low < len && nums[low] < minNum) ++low;
            
            while (low < high) {
                b = nums[low];
                c = nums[high];
                if (a + b + c > 0) {
                    high--;
                } else if (a + b + c < 0) {
                    low++;
                } else {
                    result.add(Arrays.asList(a,b,c));
                    while (low < high && nums[low] == nums[low + 1]) {
                        low++;
                    }
                    while (low < high && nums[high] == nums[high - 1]) {
                        high--;
                    }
                    low++;
                    high--;
                    
                }
            }
            
        }
        return result;
    }
}
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        
        if(nums.length < 3) return res;
        
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length-2; i++){
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            int element1 = nums[i];
            int j = i + 1;
            int k = nums.length - 1;
            while(j < k){
                if (j > i + 1 && nums[j] == nums[j-1]){
                    j++;
                    continue;
                }
                int tempSum = element1 + nums[j] + nums[k];
                if (tempSum == 0) {
                    res.add(Arrays.asList(element1, nums[j], nums[k]));
                    k--;
                    j++;
                }else if(tempSum > 0) {
                    k--;
                }else {
                    j++;
                }
            }// while loop
        }//for loop
        
        return res;
    }
}

以上是关于java 15. 3Sum(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 15. 3Sum(#)。java

java 15. 3Sum(#)。java

java 15. 3Sum(#)。java

java 15. 3Sum(#)。java

[LeetCode] 15. 3Sum Java

[LeetCode][15]3Sum解析与快速排序算法-Java实现