Files
hello-algo/ja/codes/go/chapter_searching/two_sum.go
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

34 lines
823 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// File: two_sum.go
// Created Time: 2022-11-25
// Author: reanon (793584285@qq.com)
package chapter_searching
/* 方法 1:総当たり列挙 */
func twoSumBruteForce(nums []int, target int) []int {
size := len(nums)
// 二重ループのため、時間計算量は O(n^2)
for i := 0; i < size-1; i++ {
for j := i + 1; j < size; j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}
/* 方法 2:補助ハッシュテーブル */
func twoSumHashTable(nums []int, target int) []int {
// 補助ハッシュテーブルの空間計算量は O(n)
hashTable := map[int]int{}
// 一重ループのため、時間計算量は O(n)
for idx, val := range nums {
if preIdx, ok := hashTable[target-val]; ok {
return []int{preIdx, idx}
}
hashTable[val] = idx
}
return nil
}