My Solution


  • 0
    C
        import java.util.*;
        public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
    	 
    	 quicksort(nums,0,nums.length-1);
    	 
    	 List<List<Integer>> lists = new ArrayList();
    	 		 
    	 for(int i=0;i<nums.length;i++)
    	 {
    		 int l = i-1;
    		 int r = i+1;
    		 
    		 while((l>-1) && (r<nums.length))
    		 {
    			 ArrayList<Integer> list = new ArrayList();
    			 if(nums[i]+nums[l]+nums[r] == 0)
    			 {
    				 list.add(nums[l]);
    				 list.add(nums[i]);
    				 list.add(nums[r]);
    				 l--;
    				 r++;
    				 
    				 if(!lists.isEmpty())
    				 {
    					 int u=0;
    					 int e=0;
    					 for (List<Integer> mylist : lists) {
    						 Iterator<Integer> oldIterator = mylist.iterator();
    						 Iterator<Integer> currentIterator = list.iterator();
    						 
    						 int t=0;
    						 for(;t<3;t++)
    						 {
    							 if(currentIterator.next() == oldIterator.next())
    							 {
    								 u++;
    							 }
    						 }
    		
    						 if(u == 3)
    						  {
    							 u =0;
    							 break;
    						  }
    						 
    						 e++;
    						 if(e == lists.size())
    						 {
    							lists.add(list);
    							break;
    						 }
    						 
    						 if(u <3)
    						 {
    							 u=0;
    							 continue;
    						 }
    						 
    					   }
    					}
    				 else{
    				 lists.add(list);
    				 }
    			 }
    			 else if(nums[i]+nums[l]+nums[r] > 0)
    			 {
    				 l--;
    			 }
    			 
    			 else
    			 {
    				 r++;
    			 }
    		 }
    

    // lists.add(list);
    }
    return lists;
    }

    private void quicksort(int[] nums,int s,int e) {
    	// TODO Auto-generated method stub
    	if(e>s)
    	{
    	int p = partition(nums,s,e);
    	quicksort(nums,s,p-1);
    	quicksort(nums,p+1,e);
    	}
    }
    
    private int partition(int[] nums, int s, int e) {
    	// TODO Auto-generated method stub
    	int j=s-1;
    	for(int i=s;i<e;i++)
    	{
    		if(nums[i]<=nums[e])
    		{
    			j++;
    			int tmp = nums[j];
    			nums[j] = nums[i];
    			nums[i] = tmp;
    		}			
    	}
    	
    	int tmp = nums[e];
    	nums[e] = nums[++j];
    	nums[j] = tmp;
    	
    	return j;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.