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{} } Post Views: 3 Post navigation LeetCode: Repeated Substring PatternLeetCode: Valid Triangle Number Leave a Reply Cancel replyYour email address will not be published.Comment Name Email Website