Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Two Sum

Posted on November 9, 2017July 26, 2020 by braindenny

Pic 2 numbers to get the target sum.



Similar Problems:

  • Series: TwoSum Problems & Follow-Up
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #twosum, #twopointer

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, and you may not use the same element twice.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution: sort + twopointer
## https://code.dennyzhang.com/two-sum
## Basic Ideas: Sort, then two pointer
##
## Complexity: Time O(n*log(n)), Space O(1)
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = sorted(zip(nums, range(len(nums))))
        left, right = 0, len(l)-1
        while left<right:
            v = l[left][0]+l[right][0]
            if v == target:
                return [l[left][1], l[right][1]]
            if v < target:
                left += 1
            else:
                right -= 1

  • Solution: hashmap
// https://code.dennyzhang.com/two-sum
// Basic Ideas: hashmap
//    For a given pos, look forward to find a complement one
// Complexity: Time O(n), Space O(n)
func twoSum(nums []int, target int) []int {
    m := map[int]int{} // value to position
    for i, v := range nums {
        m[v] = i
    }
    for i, v := range nums {
        if index, ok := m[target-v]; ok {
            if index != i {
                return []int{i, index}
            }
        }
    }
    return []int{}
}
linkedin
github
slack

Post Views: 3
Posted in BasicTagged #twopointer, #twosum

Post navigation

LeetCode: Repeated Substring Pattern
LeetCode: Valid Triangle Number

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.