Java solution, 12m, only beat 19%, but easy to understand, can someone find optimum way


  • 1
    M

    public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    // Iterator iterator = list.iterator();
    int index;
    if (nums.length < 3)
    return list;

    	Arrays.sort(nums);
    	
    	for (int i = -1;i < nums.length - 2;) {
    		do {
    			i++;
    		} while (i - 1 >= 0 && i < nums.length - 2 && nums[i] == nums[i - 1]);
    		
    		for (int j = i;j < nums.length - 1;) {
    			do {
    				j++;
    			} while (j - 1 > i && j < nums.length - 1 && nums[j] == nums[j - 1]);
    
    			index = Arrays.binarySearch(nums, -nums[i] - nums[j]);
    			while (index >= 0 && index + 1 < nums.length && nums[index] == nums[index + 1]) {
    				index++;
    			}
    			if (index > j) {
    				list.add(Arrays.asList(nums[i], nums[j], nums[index]));
    			}
    		}
    	}
    
    	return list;
    }
    

    }


Log in to reply
 

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