Three Sum solution easiest and optimal way


  • 0
    N
    class Solution {
      public List<List<Integer>> threeSum(int[] nums) {
    
    		Arrays.sort(nums);
    		List<List<Integer>> combinedList = new ArrayList<List<Integer>>();
    		Map<Integer, Integer> map = new HashMap<>();
    		int target = 0;
    		for (int i = 0; i < nums.length; i++) {
    			map.put(nums[i], i);
    		}
    
    		for (int j = 0; j < nums.length; j++) {
    			int newTarget = 0;
    			newTarget = target - nums[j];
    			int firstIndex = j;
    			for (int i = firstIndex + 1; i < nums.length; i++) {
    				int complement = newTarget - nums[i];
    
    				if ((nums[firstIndex] > 0 && nums[i] > 0 && complement > 0)
    						|| (nums[firstIndex] < 0 && nums[i] < 0 && complement < 0)) {
    
    					break;
    				}
    				if (map.containsKey(complement) && map.get(complement) > i) {
    					ArrayList<Integer> initialList = new ArrayList<Integer>();
    					initialList.add(nums[firstIndex]);
    					initialList.add(nums[i]);
    					initialList.add(complement);
    					if (!combinedList.contains(initialList)) {
    						combinedList.add(initialList);
    
    					}
    				}
    			}
    
    		}
    		return combinedList;
    	}
    }
    

Log in to reply
 

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