LeetCode moderate problem (b)

Topic one:

Given an array nums n comprises integers, determines whether there are three elements a, b, c nums such that a + b + c = 0? All the conditions are not satisfied to find duplicate triples.

Note: The answer can not contain duplicate triples.

For example, given the array nums = [-1, 0, 1, 2, -1, -4],

Meet the requirements set of triples as:
[
[-1, 0, 1],
[-1, -1, 2]
]

 

Analysis : This is a triple summation problem

1, the type first defined tuple returned, List <List <Integer >> new new ANS = the ArrayList <> () ;

2, the beginning of the array to sort , Arrays.sort (nums);

3, traversed by a pointer to an entire array for (int i = 0; i <num.lenght; i ++)

4, then set two pointers, respectively. 1 + I = L,. 1-len = R & lt ;

5, the next start sum is judged; if (nums [i] + nums [l] + nums [r] == 0) to l ++, r--;

6, of course, should be deposited into ans.add (Arrays.asList (the nums [I], the nums [L], the nums [R & lt])) ;

7, in this process may be repeated to produce , if (nums [i]> 0) break, if (i> && nums [i] == nums [i-1]) continue; while (nums [l] == nums [l +1]) l ++; r the same;

8, if the different sum <0, l ++; sum> 0, r--;

9, return ANS;

 

Specific code:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        List<List<Integer>> ans=new ArrayList<>();
        int len=nums.length;        
        if(nums==null||len<3) return ans;
        
        Arrays.sort(nums);
        
        for(int i=0;i<len;i++)
        {
            int l=i+1,r=len-1;
            if(nums[i]>0) break;
            if(i>0&&nums[i]==nums[i-1]) continue;
            while(l<r)
            {
                int sum=nums[i]+nums[l]+nums[r];
                if(sum==0)
                {
                    ans.add(Arrays.asList(nums[i],nums[l],nums[r]));
                    while(l<r&&nums[l]==nums[l+1]) l++;
                    while(l<r&&nums[r]==nums[r-1]) r--;
                    l++;
                    r--;
                }
                else if(sum<0) l++;
                else if(sum>0) r--;                    
            }
        }         
        Return year; 
    }         
}

 

Guess you like

Origin www.cnblogs.com/Optimism/p/11327405.html