Skip to content

Commit 54374ec

Browse files
committed
add TopKFrequentElements - Day 17
1 parent 257cbe1 commit 54374ec

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.concept.scala.leetcode_30days_challenge_July2020
2+
3+
import scala.collection.mutable.ListBuffer
4+
5+
/** *
6+
* Day 17
7+
*
8+
* @todo Given a non-empty array of integers, return the k most frequent elements.
9+
* @example Example 1:
10+
*
11+
* Input: nums = [1,1,1,2,2,3], k = 2
12+
* Output: [1,2]
13+
* Example 2:
14+
*
15+
* Input: nums = [1], k = 1
16+
* Output: [1]
17+
* @note You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
18+
* Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
19+
* It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
20+
* You can return the answer in any order.
21+
*
22+
*/
23+
object TopKFrequentElements {
24+
def main(args: Array[String]): Unit = {
25+
println(topKFrequent(Array(1, 1, 1, 2, 2, 3), 2).mkString(","))
26+
println(topKFrequent(Array(1), 1).mkString(","))
27+
28+
}
29+
30+
31+
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
32+
def priorityLogic(topKList: ListBuffer[(Int, Int)], tuple: (Int, Int)): ListBuffer[(Int, Int)] = {
33+
if (topKList.length < k)
34+
topKList += tuple
35+
else {
36+
//val topKMin: (Int, Int) = topKList.sortBy(_._2).head
37+
val topKMin: (Int, Int) = topKList.minBy(_._2)
38+
if (tuple._2 > topKMin._2) topKList -= topKMin += tuple
39+
}
40+
topKList
41+
}
42+
43+
nums.groupBy(identity).mapValues(_.length).foldLeft(ListBuffer[(Int, Int)]())(priorityLogic).map(_._1).toArray
44+
}
45+
46+
47+
}

0 commit comments

Comments
 (0)