leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.
Introduction to golang + algorithm I will solve it with go and Python to strengthen the brain.
Given an array of integers that is already *sorted in ascending order*, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example 1:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Example 2:
Input: numbers = [2,3,4], target = 6 Output: [1,3]
Example 3:
Input: numbers = [-1,0], target = -1 Output: [1,2]
Loop as many times as there are numbers
Store the value in dic and exit if target-num exists
Answer code
def twoSum(self, numbers, target):
dic = {}
for i, num in enumerate(numbers):
if target-num in dic:
return [dic[target-num]+1, i+1]
dic[num] = i
--I'll write it in Go too!
func twoSum(numbers []int, target int) []int {
m := make(map[int]int)
for i := 0; i < len(numbers); i++ {
idx, ok := m[target-numbers[i]]
if ok {
return []int{idx + 1, i + 1}
}
m[numbers[i]] = i
}
return nil
}
Recommended Posts