zoukankan      html  css  js  c++  java
  • 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:

    The solution set must not contain duplicate triplets.

    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;
        }
    }

    数组问题注意:下标越界

    时间复杂度:O(n2),通过两个指针向中间夹逼的方法使得两个数求和的时间复杂度从O(n2)->O(n)。

  • 相关阅读:
    CocoaPods 的简单快速安装方法
    macOS Catalina new Shell,解决 The default interactive shell is now zsh
    Mac入门--通过homebrew下载过慢问题
    Mac下安装Android Studio
    Mac更新catalina之后有道词典闪退的解决办法
    mac系统下安装Java开发环境(一)——JDK安装
    聊天案例
    ios中常用k线
    ubuntu连接蓝牙鼠标
    image_transport
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10770353.html
Copyright © 2011-2022 走看看