Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

2 Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

nums = [2, 7, 11, 15] target = 9

returns

[0, 1]

because nums[0] + nums[1] = 2 + 7 = 9.

UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully.

def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    memo = {}
    for i in range(len(nums)):
        compliment = memo.get(nums[i])
        if compliment != None:
            return [compliment, i]
        memo[target-nums[i]] = i
// @flow
const twoSum = (nums: ?number[], target: number) => {
  var memo: {
    [compliment: number]: number
  } = {}
  if (nums == null) return null;
  for (var i = 0; i < nums.length; i++) {
    if (memo[nums[i]] != null) {
      return [memo[nums[i]], i]
    }
    memo[target - nums[i]] = i
  }
}

Previous3 SumNextMaximum Subarray

Last updated 6 years ago