Skip to content

3 Sum in golang #2

Closed
Closed
@ralic

Description

@ralic

The code runs for ~1500ms compared to the Java's solution 60ms. I am afraid that I may need some help in golang, would you mind check the logic in Java and see if it's possible to make a faster go version... ?

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        List<Integer> list;
        List<List<Integer>> retList = new  LinkedList<>();
        Arrays.sort(nums);
        for( int i = 0; i < nums.length && nums[i] <= 0; i++){
            if( i > 0 && nums[i] == nums[i-1])
                continue;
            int sum = (-1)*nums[i], front = i + 1, behin = nums.length - 1;
            while( front < behin )
                if( nums[front] + nums[behin] > sum) 
                    behin--;
                else if( nums[front] + nums[behin] < sum) 
                    front++;
                else{
                    list = new LinkedList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[front]);
                    list.add(nums[behin]);
                    retList.add(list);
                    while( front<behin && nums[front]==nums[front+1]) front++;
                    while( front<behin && nums[behin]==nums[behin-1]) behin--;
                    front++;
                    behin--;
                }
        }
        return retList;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions