LeetCode 1. Two Sum | HashMap | Java

 Solution 1: Brute Force

class Solution {

    public int[] twoSum(int[] nums, int target) {

        int len = nums.length;

        for(int i = 0; i < len; i++) {

            for(int j = i + 1; j < len; j++) {

                if(nums[i] + nums[j] == target)

                    return new int[] {i, j};

            }

        }

        return null;

    }

}

Complexity Time: O(n^2)
Complexity Space: O(1)

Solution 2: Using Hashmap


class Solution {

    public int[] twoSum(int[] nums, int target) {

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

       

        for (int i = 0; i < nums.length; i++) {

            Integer remaining = (Integer)(target - nums[i]);

            if(map.containsKey(remaining))

                return new int[] {map.get(remaining), i};

            map.put(nums[i], i);

        }

        return null;

    }

}


Complexity Time: O(n)
Complexity Space: O(n)





Comments

Popular posts from this blog

LeetCode 2. Add Two Numbers | LinkedList

LeetCode 9. Palindrome Number