Mister-Hope

1. Two SumMister-HopeC++JavaJavaScriptPython3TypeScript

C++

/*
 * Runtime: 188 ms, faster than 36.71% of C++ online submissions for Two Sum.
 *
 * Memory Usage: 52.9 MB, less than 13.71% of C++ online submissions for Two
 * Sum.
 */

#include <unordered_map>
#include <vector>
using namespace std;

class Solution {
 public:
  vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> prevMap;

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

      if (prevMap.count(j)) return {prevMap[j], i};
      prevMap[nums[i]] = i;
    }

    return {};
  }
};

Java

/*
 * Runtime: 10 ms, faster than 41.97% of Java online submissions for Two Sum.
 *
 * Memory Usage: 56.5 MB, less than 6.02% of Java online submissions for Two Sum.
 */

import java.util.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++) {
      int j = target - nums[i];

      if (map.containsKey(j))
        return new int[] {map.get(j), i};

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

    throw new IllegalArgumentException("No solution");
  }
}

JavaScript

/*
 * Runtime: 112 ms, faster than 48.98% of JavaScript online submissions for Two Sum.
 *
 * Memory Usage: 48.3 MB, less than 5.73% of JavaScript online submissions for Two Sum.
 */

const twoSum = (nums, target) => {
  const arr = [];

  for (let i = 0; i < nums.length; i++) {
    let j = arr[target - nums[i]];
    if (j !== undefined) return [j, i];
    arr[nums[i]] = i;
  }

  throw new Error("No solution");
};

Python3

# Runtime: 476 ms, faster than 32.13% of Python3 online submissions for Two Sum.
#
# Memory Usage: 27.9 MB, less than 17.63% of Python3 online submissions for Two Sum.

class Solution:
  def twoSum(self, nums: List[int], target: int) -> List[int]:
    prevMap = {}
    
    for i, v in enumerate(nums):
      j = target - v
      if j in prevMap:
        return [prevMap[j], i]
      prevMap[v] = i
    return

TypeScript

/*
 * Runtime: 124 ms, faster than 50.73% of TypeScript online submissions for Two Sum.
 *
 * Memory Usage: 48.7 MB, less than 5.74% of TypeScript online submissions for Two Sum.
 */

const twoSum = (nums: number[], target: number): number[] => {
  const arr = [];

  for (let i = 0; i < nums.length; i++) {
    let j = arr[target - nums[i]];
    if (j !== undefined) return [j, i];
    arr[nums[i]] = i;
  }

  throw new Error("No solution");
};