349. Intersection of Two Arrays - #13
Conversation
|
|
||
| - これは確か解法がたくさんある問題だったはず。なるべく多く解法を思いつきたいな。 | ||
|
|
||
| ### 解法1: set の & を使う |
There was a problem hiding this comment.
ここでは触れられていませんが、片方だけHashSet(例: nums1_set)を作る解法もあります。
もう片方(nums2)は要素を一個一個取り出し、含まれていたらintersectionに追加してHashSetから値を削除(重複防止)するという具合です。
There was a problem hiding this comment.
ありがとうございます。
確かにそのような解き方もできますね!
step4 として追加しました。
8293b19
| #### 参考にした回答 | ||
|
|
||
| - https://github.com/hayashi-ay/leetcode/pull/21/changes の 4th |
There was a problem hiding this comment.
コードに対するコメントではないのですが,markdownに記載する順番について,現状は以下のような順番になっていると思いますが,「参考にした回答」は前提であるので,先に提示してもらったほうが読みやすいな,と思いました.
### 解法X
- 考えたこと
code-block
#### 参考にした回答たとえば以下のほうが,上から順に読んでいけるので嬉しいです.
### 解法X
- 参考にした回答
- https://github.com/xxxx/yyyy
- 考えたこと
code-blockThere was a problem hiding this comment.
ありがとうございます。
確かにおっしゃる通りだと思ったので以降の PR で反映しています。
https://github.com/kazizi55/coding-challenges/pull/14/changes
https://github.com/kazizi55/coding-challenges/pull/15/changes
| ```py | ||
| class Solution: | ||
| def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: | ||
| seen_in_nums1 = [False] * 1001 |
There was a problem hiding this comment.
単に質問なんですが,1000ではなく1001 としたのはなぜでしょう?
+1した理由があれば知りたいです.慣習とかですか?
There was a problem hiding this comment.
大きい方のサイズにするとかでもよいかもしれませんね.
max(len(nums1), len(nums2))
There was a problem hiding this comment.
単に質問なんですが,1000ではなく1001 としたのはなぜでしょう?
これは 0 <= nums1[i], nums2[i] <= 1000 という LeetCode 上の制約に対応するためです。[0] から [1000] まで1001個の要素のいずれかに入力が対応しうるためですね。
There was a problem hiding this comment.
大きい方のサイズにするとかでもよいかもしれませんね.
ありがとうございます。
step4 として追加しています。LeetCode の制約を超えた入力にも対応できる点でいいなと思いました。
8293b19
ちなみに seen_in_nums1 の要素数は nums1 と nums2 の中で最大の数を設定する必要があるため、以下のように書いています。
seen_in_nums1 = [False] * (
max(
max(nums1),
max(nums2)
)+1
)| index2 += 1 | ||
| continue | ||
| intersection.append(nums1[index1]) | ||
| index1 += 1 |
There was a problem hiding this comment.
append したあとに、 append したものとは異なる値までインデックスを進めるという実装も考えられます。
https://leetcode.com/problems/intersection-of-two-arrays/description/
Next: https://leetcode.com/problems/unique-email-addresses/