Skip to content

Create 347.md#9

Open
hiroki-horiguchi-dev wants to merge 3 commits intomainfrom
heap-priorityqueue-347
Open

Create 347.md#9
hiroki-horiguchi-dev wants to merge 3 commits intomainfrom
heap-priorityqueue-347

Conversation

@hiroki-horiguchi-dev
Copy link
Owner

347. Top K Frequent Elementsを解きました。
レビューお願いします。

@hiroki-horiguchi-dev hiroki-horiguchi-dev self-assigned this Mar 20, 2026
@hiroki-horiguchi-dev hiroki-horiguchi-dev changed the title Create 307.md Create 347.md Mar 20, 2026
}

int idx = 0;
for (int i = bucket.length - 1; i >= 0 && idx < k; i--) {

Choose a reason for hiding this comment

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

idxがkになったら、breakされるように書かれているので、idx < kはなくても良いですかね。

frequency.put(num, frequency.getOrDefault(num, 0) + 1);
}

PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());

Choose a reason for hiding this comment

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

データ構造ではなく、実際に入っている中身で変数名を決めると良いかもです。

私ならk_topsと名付けます。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
そうですね、取り込みます。

Comment on lines +32 to +33
for (int key : frequency.keySet()) {
int value = frequency.get(key);

Choose a reason for hiding this comment

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

keyはnum, valueはfrequencyで良いかもです。
かぶってしまうので、元のfrequencyはnumTo Frequencyとするのはどうでしょう。
map系で、keyToValueという命名の仕方をしている人は多い印象です。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
そっちの方がいいですね、取り込みます。

class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] result = new int[k];
HashMap<Integer, Integer> frequency = new HashMap<>();
Copy link

Choose a reason for hiding this comment

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

型を Map<Integer, Integer> とするのをよく見かけます。このあたりは所属するチームの平均的な書き方に合わせることをお勧めいたします。

```java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] result = new int[k];
Copy link

Choose a reason for hiding this comment

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

変数を使用箇所よりだいぶ前で定義をすると、読み手は使用箇所まで変数の定義を覚えていなければならず、短期記憶を圧迫してしまいます。変数は使用箇所の直前で定義することをお勧めいたします。

bucket[value].add(key);
}

int idx = 0;
Copy link

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

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