Skip to content

1. Two Sum

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

js
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = function(nums, target) {
  const map = {}

  for (let i = 0; i < nums.length; i++) {
    const num = nums[i]

    if (map[target - num] !== undefined) {
      return [map[target - num], i]
    }

    if (!map[num]) {
      map[num] = i
    }
  }
}
py
class Solution(object):

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup = {}
        for i, num in enumerate(nums):
            if target - num in lookup:
                return [lookup[target - num], i]
            if num not in lookup:
                lookup[num] = i
go
func twoSum(nums []int, target int) []int {
  lookup := make(map[int]int)

  for i, num := range nums {
    if index, ok := lookup[target-num]; ok {
      return []int{index, i}
    }
    lookup[num] = i
  }

  return []int{-1, -1}
}
rust
use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut lookup: HashMap<i32, i32> = HashMap::new();
        for (index, &num) in nums.iter().enumerate() {
            match lookup.get(&(target - num)) {
                Some(&i) => return vec![i, index as i32],
                None => lookup.insert(num, index as i32),
            };
        }
        return vec![-1, -1];
    }
}