ARTS Week 28

Algorithm

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
import java.util.SortedMap;class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> numCount = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
numCount.put(nums[i], numCount.getOrDefault(nums[i], 0) + 1);
}
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
for (int key : numCount.keySet()) {
int count = numCount.get(key);
if (pq.size() == k) {
if (pq.peek()[1] < count) {
pq.poll();
pq.offer(new int[]{key, count});
}
} else {
pq.offer(new int[]{key, count});
}
}
int[] ans = new int[k];
for (int i = 0; i < k; i++) {
ans[i] = pq.poll()[0];
}
return ans;
}
}

Review

  • “I don’t have anything interesting to say”: the author doesn’t think he has too many strong, unique, novel ideas to share.
  • “I’m not a good programmer”: the author believes that most of his skills are just beginner level and there is no need to share them.
  • “I don’t think it’s good CV building”: The author thinks that the average blog is not enough as a good resume building platform, if you only have a blog, maybe no one will visit.

Tip

.PHONY : clean
clean:
rm $(OBJS) *.o a.out

Share

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KeepNewbie_yan

A programmer. Share knowledge of programming, operating system, Linux kernel, and reading, thinking etc. Let us maintain a beginner mend and grow together!