Sunday, January 21, 2018

[2018-Interview] Two Sum

Original question: https://leetcode.com/problems/two-sum/description/

My answer: Actually we can combine two for loop into one



class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 1) {
            return new int[0];
        }
        // solution: Map<target - element, index>
        Map<Integer, Integer> targetRemainingIndex = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i ++) {
            int targetRemaining = target - nums[i];
            targetRemainingIndex.put(targetRemaining, i);
        }
        for (int i = 0; i < nums.length; i ++) {
            // edge case where target is 6, nums is [3, 2, 4]
            if (targetRemainingIndex.containsKey(nums[i]) && 
                 targetRemainingIndex.get(nums[i]) != i // don't sum with itself
            ) {
                int [] result = new int[2];
                result[0] = i;
                result[1] = targetRemainingIndex.get(nums[i]);
                return result;
            }
        }
        return new int[0];
    }
}

No comments:

Post a Comment