Skip to content

373. Find K Pairs with Smallest Sums#10

Open
n6o wants to merge 3 commits intomainfrom
find-k-pairs-with-smallest-sums
Open

373. Find K Pairs with Smallest Sums#10
n6o wants to merge 3 commits intomainfrom
find-k-pairs-with-smallest-sums

Conversation

@n6o
Copy link
Copy Markdown
Owner

@n6o n6o commented Feb 7, 2026

今回の問題

Find K Pairs with Smallest Sums - LeetCode

使用言語

Go

次に解く問題

Two Sum - LeetCode

})
}

result := make([][]int, 0, k)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

現状の方が変数が短くてGoっぽいのですが、smallestPairs とか smallestIndexPairs とかにすると、何を詰めるのか分かりやすいかなと思いました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。
ご指摘の通り、「何なのか」を表す方が読みやすいです。

戻り値はとりあえず result にしてそのままにしていることが多いので、意識するようにします。

@mamo3gr
Copy link
Copy Markdown

mamo3gr commented Feb 7, 2026

特に違和感ありませんでした。

単なる感想ですが、Goだと毎回heapインターフェースを満たすコードを書くのが大変そうだなと思いました。


### 1.

とりあえず総当たりで実装した。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

実装前に時間計算量は求めましたでしょうか。また、時間計算量から実行時間は推定されましたでしょうか。
実行時間の推定方法が分からない場合は、以下のコメントが参考になると思います。
Yuto729/LeetCode_arai60#16 (comment)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。

このときは実行時間までは推定しておりませんでした。
今後、TLEすると考えた場合、一度実行時間の推定まですることを習慣にします。

時間計算量

  • num1 の長さ: N、nums2の長さをMとする
  • ペアは最大10^10個できる: O(NM)
    • ペアごとにヒープ操作: O(log k)
  • k 個の最小要素を取り出す
    • 取り出すヒープ操作: O(log k)
  • 時間計算量は O(NM log k)

実行時間の推定

  • go は 10^8 ステップ/秒とする
  • N, M の最大値は10^5なので NM は10^10
  • k は 10^4
  • 10^10 / 10^8 * 4 = 400秒かかる
  • TLEする

return result
}

type pair struct {
Copy link
Copy Markdown

@nodchip nodchip Feb 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pair は通常 2 つの要素を持つデータ構造だと思います。 IndexesAndSum や IndexPairAndSum はいかがでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。
ご指摘の通り、余分な要素 sum があるため、それが明示される名前が適切ですね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants