Conversation
|
|
||
| k_smallest_pairs.append([nums1[index1], nums2[index2]]) | ||
| visited.add((index1, index2)) | ||
| if index1+1 < len(nums1) and (index1+1, index2) not in visited: |
There was a problem hiding this comment.
- の両側にスペースを空けることをお勧めいたします。
https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
https://google.github.io/styleguide/pyguide.html#36-whitespace
Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @).
| class Solution: | ||
| def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: | ||
| k_smallest_pairs = [] | ||
| visited = set() |
There was a problem hiding this comment.
visited という変数名は、グラフ等ですでに探索済みのノードを表すときに見かけますが、今回のように処理済みであることを表すにはやや不適切なように思います。 proceeded または proceeded_index_pairs はいかがでしょうか?
There was a problem hiding this comment.
コメントありがとうございます。
グラフ探索っぽい感覚があったほうがコード全体の理解が早いかなくらいの気持ちで名付けてました。確かに、状況的にproceededとかの方がわかりやすいですね。
|
|
||
| k_smallest_pairs.append([nums1[index1], nums2[index2]]) | ||
| visited.add((index1, index2)) | ||
| if index1+1 < len(nums1) and (index1+1, index2) not in visited: |
There was a problem hiding this comment.
同じような処理が 2 度登場するため、関数化して共通化してもよいと思います。
| ``` | ||
| (i, j)にたどり着くためのルートが一本に定まる様にしてある。 | ||
|
|
||
| 個人的には、自分の書いたもののほうが読みやすかった。自分の書いたものは対称的かつ、dijkstraの延長上のものと理解できること、こちらのコードは微妙に対称性が崩れており、その理由を考えるのに時間がかかることが原因だと思う。 |
There was a problem hiding this comment.
対称にしないのならば、heapq.merge 使う手もありますかね。
これは、iterator をいくつか引数にとってマージします。
| 個人的には、自分の書いたもののほうが読みやすかった。自分の書いたものは対称的かつ、dijkstraの延長上のものと理解できること、こちらのコードは微妙に対称性が崩れており、その理由を考えるのに時間がかかることが原因だと思う。 | ||
| - `next_pair`変数の代わりに、`sum_with_each_index`という変数名を使っていた。 | ||
| - https://github.com/goto-untrapped/Arai60/pull/56 | ||
| - heappushする箇所を関数化するのもあり |
There was a problem hiding this comment.
これ、同じようなもので範囲チェックが異なるものが2つある感じがするので、まとめるのはひとつでしょう。
|
step3におけるvisitedを使用しないパターンもあって、興味深かったので共有しておきます。 |
| def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: | ||
| k_smallest_pairs = [] | ||
| visited = set() | ||
| next_pair = [] |
| (nums1[index1] + nums2[index2 + 1], index1, index2 + 1) | ||
| ) | ||
| return k_smallest_pairs | ||
| ``` No newline at end of file |
There was a problem hiding this comment.
訪問済み(処理済み)の座標をO(2n)の空間計算量で管理する方法もあります
TORUS0818/leetcode@09636a1#diff-12341a70069caa7ec44aba610c42a0123605c2680c11a88728158764788bead7
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/