LeetCode- TWO SUM

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Use a loop instead of two loops.

When we insert the elements into the table,  we also check if the current complement already exists in the table. If it exists, we find the solution.

  • Time complexity : O(n). Travel the array numbers.
  • Space complexity : O(n). Depend on how many elements are stored in the table.
    public static int[] twoSum(int[] nums, int target) {
        Map map = new HashMap();

        for(int i = 0; i < nums.length; i++){
            int different = target - nums[i];

            if(map.containsKey(different)){
                return new int[] {map.get(different), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

Reference:
https://leetcode.com/problems/two-sum/solution/

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s