1. Two Sum

  1. brute force, O(n^2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    return new int[] {i, j};
                }
            }
        }
        throw new RuntimeException("not found");
    }
}

2. hashMap

O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int cur = nums[i];
            if (map.containsKey(target - cur)) {
                return new int[]{map.get(target - cur), i};
            }
            map.put(cur, i);
        }
        throw new RuntimeException("not found");
    }
}

js

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let map = [];
    for (let i = 0; i < nums.length; i++) {
        map[nums[i]] = i;
    }
    
    for (let i = 0; i < nums.length; i++) {
        const remainder = target - nums[i];
        
        if (map[remainder] && map[remainder] !=i) {
            return [i, map[remainder]];
        } 
    }
};

Last updated