Skip to content

K Closest Points To Origin#123

Open
tom4649 wants to merge 1 commit into
mainfrom
973.K-Closest-Points-to-Origin
Open

K Closest Points To Origin#123
tom4649 wants to merge 1 commit into
mainfrom
973.K-Closest-Points-to-Origin

Conversation

@tom4649
Copy link
Copy Markdown
Owner

@tom4649 tom4649 commented May 31, 2026

@tom4649 tom4649 force-pushed the 973.K-Closest-Points-to-Origin branch from d7714e3 to 8eb4f83 Compare May 31, 2026 07:06

n = len(points)として

時間計算量: O(n+klog n)、空間計算量: O(n)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

heapの長さをkで絞りつつpushしていけば、空間計算量はO(k)で済ませることができそうです。その場合、時間計算量はO(n log k)ですかね。(下の方に書いてありました)
Arai60の範囲でヒープ等を使ってk番目までを取る問題があった気がするので、発想はそれと同じような気がします。

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.

Arai60の問題は以下だと思います。
https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

heapの長さをkで保つ解法の発想も持っておこうと思います。今回は他の方のコードを見るまで思い浮かびませんでした。

return k_closest_helper(start, pivot_index_after - 1)

k_closest_helper(0, len(points) - 1)
return points[: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.

念のため、ぐらいのコメントです。
このアルゴリズムは練習・選択肢の幅としてはよいと思いますが、副作用が「常に完全にpointsをソートするわけではなく、この問題において必要な範囲のみpointsを並び替える」という内容なので、pointsが使い捨ての想定でなければかなり関数として気持ち悪いとは思います。
(もちろん、一時変数に対してこういった処理を適用することはよくあるとは思います。関数としてのこの問題の想定解は長さkのheapを使うものかなという気がします。)

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.

pointsが使い捨ての想定でなければかなり関数として気持ち悪い

このような感覚は持っていませんでした。こういったコードを俯瞰するような視点を持てるようになりたいです。

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.

2 participants