Conversation
| while (i < uniqueNums1.length || j < uniqueNums2.length) { | ||
| if (uniqueNums1[i] == uniqueNums2[j]) { | ||
| intersection.add(uniqueNums1[i]); | ||
| i ++; |
There was a problem hiding this comment.
Javaにあまり詳しくないのですが、インクリメント演算子と変数の間にスペースを空けるのは一般的なのでしょうか?
There was a problem hiding this comment.
一般的ではないですね。。。
自分でも何故スペースを入れたのか分からないです。
ありがとうございます。
| List<Integer> intersection = new ArrayList<>(); | ||
| int i = 0; | ||
| int j = 0; | ||
| while (i < uniqueNums1.length || j < uniqueNums2.length) { |
There was a problem hiding this comment.
こちら&&にしないと配列外参照でエラーになりました
| while (i < uniqueNums1.length || j < uniqueNums2.length) { | |
| while (i < uniqueNums1.length && j < uniqueNums2.length) { |
There was a problem hiding this comment.
失礼しました。仰る通り&&が正解です。
お恥ずかしい限りです。
| int[] uniqueNums1 = Arrays.stream(nums1).distinct().toArray(); | ||
| int[] uniqueNums2 = Arrays.stream(nums2).distinct().toArray(); | ||
| Arrays.sort(uniqueNums1); | ||
| Arrays.sort(uniqueNums2); |
There was a problem hiding this comment.
以下のように一行で書いてもよいかなと思いました
| int[] uniqueNums1 = Arrays.stream(nums1).distinct().toArray(); | |
| int[] uniqueNums2 = Arrays.stream(nums2).distinct().toArray(); | |
| Arrays.sort(uniqueNums1); | |
| Arrays.sort(uniqueNums2); | |
| int[] uniqueNums1 = Arrays.stream(nums1).sorted().distinct().toArray(); | |
| int[] uniqueNums2 = Arrays.stream(nums2).sorted().distinct().toArray(); |
There was a problem hiding this comment.
ご提案いただいた書き方の方がスマートですね。
distinct()があるくらいならsorted()もあるはずと書きながら気づくべきでした。
ありがとうございます!
| intersection.retainAll(Arrays.stream(nums2).boxed().toList()); | ||
| return intersection.stream().mapToInt(Integer::intValue).toArray(); | ||
| } | ||
| } |
There was a problem hiding this comment.
Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
return Arrays.stream(nums2).filter(set::contains).distinct().toArray();とかですかね。まあ、ループを素朴に回したほうが読みやすい気がします。
There was a problem hiding this comment.
StreamでSetに加工することもできましたね。
私も素朴にループを回した方が読みやすい気がします。。。
| public int[] intersection(int[] nums1, int[] nums2) { | ||
| List<Integer> intersection = new ArrayList<>(Arrays.stream(nums1).distinct().boxed().toList()); | ||
| intersection.retainAll(Arrays.stream(nums2).boxed().toList()); | ||
| return intersection.stream().mapToInt(Integer::intValue).toArray(); |
There was a problem hiding this comment.
そうですね。行数が増えても素朴にループを回す方が短時間で理解しやすいコードになる気がします。
コメントありがとうございます!
今回解いた問題:
349. Intersection of Two Arrays
次に解く問題:
929. Unique Email Addresses