LeetCodeに毎日挑戦してみた 167. Two Sum II - Input array is sorted(Python、Go)


Leetcodeとは

leetcode.com
ソフトウェア開発職のコーディング面接の練習といえばこれらしいです。
合計1500問以上のコーデイング問題が投稿されていて、実際の面接でも同じ問題が出されることは多いらしいとのことです。

golang入門+アルゴリズム脳の強化のためにgoとPythonで解いていこうと思います。

37問目(問題167)

167. Two Sum II - Input array is sorted

問題内容

  • 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]

考え方

  1. numbersの数だけループを回します

  2. dicに値を格納していき、target-numが存在したら終了します

解答コード

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
  • Goでも書いてみます!
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
}