zoukankan      html  css  js  c++  java
  • leetcode : 3 sum

    Given an array S of n integers, are there elements abc in S 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.

    For example, given array S = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]


    tag : two pointers

    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
    		if(nums == null || nums.length < 3){
    			return result;
    		}
    		
    		Arrays.sort(nums);
    		
    		for(int i = 0 ; i < nums.length - 2; i++){
    			int a = nums[i];
    			if(i != 0 && nums[i-1] == nums[i]){
    				continue;
    			}
    			
    			int left = i + 1;
    			int right = nums.length - 1;
    			
    			while(left < right){
    				int b = nums[left];
    				int c = nums[right];
    				int sum = a + b + c;
    				if(sum == 0){
    					List<Integer> tmp = new ArrayList<Integer>();
    					tmp.add(a);
    					tmp.add(b);
    					tmp.add(c);
    					result.add(tmp);
    					left++;
    					right--;
    					while(left < right && nums[left] == nums[left-1]){
    						left ++;
    					}
    					while(left < right && nums[right + 1] == nums[right]){
    						right --;
    					}
    				}else if(a + b + c < 0){
    					left ++;
    				}else{
    					right --;
    				}
    			}
    		}
    		return result;
        }
    }
    

      

  • 相关阅读:
    Python基础四
    Python基础三
    Python基础二
    Python基础一
    JAVA测试
    国庆随笔
    ATM-JAVA程序 //程序有5处相同错误,找不出原因 转账功能没有实现,修改密码来不及实现了
    JAVA程序测试感受
    第八周
    第七周
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6399094.html
Copyright © 2011-2022 走看看