3sum issue

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if( num == null || num.length == 0 )
        {
            return result;
        }
        Arrays.sort( num );

        for( int i = 0; i < num.length; i++ )
        {
            int k = num.length - 1;
            for( int j = i+1; j < num.length;j++ )
            {
                if( num[j] == num[j-1] )
                {
                //    continue;
                }
                while( num[j] + num[k] + num[i] > 0 && k > j )
                {
                    k--;
                }
                while( num[j] + num[k] + num[i] < 0 && j < k)
                {
                    j++;
                }
                if( num[j] + num[k] + num[i] == 0 && j != k )
                {
                    ArrayList<Integer> arr = new ArrayList<Integer>();
                    arr.add( num[i] );
                    arr.add( num[j] );
                    arr.add( num[k] );
                    if( !result.contains(arr) )
                    {
                        result.add( arr );
                    }
                }
            }
        }
        return result;

    }
}

I pass the ‘judge small’, but failed the ‘judge large’,

 

Run Status: Time Limit Exceeded

Last executed input

[-6,-8,-9,4,-14,6,-10,7,12,13,4,9,7,14,-12

 

still need some improvements

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s