From b2100f864390d979075174a7e1901ca6ce1ce365 Mon Sep 17 00:00:00 2001 From: Anmollenka Date: Fri, 25 Sep 2020 23:37:36 +0530 Subject: [PATCH 1/2] Changes made --- LeetCode/top_k_frequent.py | 21 +++++++++++++++++++++ test/test_top_frequent.py | 8 ++++++++ 2 files changed, 29 insertions(+) create mode 100644 LeetCode/top_k_frequent.py create mode 100644 test/test_top_frequent.py diff --git a/LeetCode/top_k_frequent.py b/LeetCode/top_k_frequent.py new file mode 100644 index 0000000..ef6b819 --- /dev/null +++ b/LeetCode/top_k_frequent.py @@ -0,0 +1,21 @@ +# Given a non-empty array of integers, return the k most frequent elements. + +class Solution: + def topKFrequent(self, nums:List[int], k: int) -> List[int]: + m,v,ma={},[],0 + for i in nums: + if i in m: + m[i]+=1 + else: + m[i]=1 + if m[i]>ma: + ma=m[i] + while k!=0: + for i in m: + if k==0: + break + if m[i]==ma: + v.append(i) + k-=1 + ma-=1 + return v \ No newline at end of file diff --git a/test/test_top_frequent.py b/test/test_top_frequent.py new file mode 100644 index 0000000..50dbcb3 --- /dev/null +++ b/test/test_top_frequent.py @@ -0,0 +1,8 @@ +import sys +import os +sys.path.append(os.path.join(sys.path[0], '..')) +from LeetCode.top_k_frequent import Solution + +def test_topk(): + s = Solution() + assert s.topKFrequent([1,1,1,2,2,3],2) == [1,2] \ No newline at end of file From b2e0651fb28bb7686936e08ad0a62051453ad291 Mon Sep 17 00:00:00 2001 From: Anmollenka Date: Sat, 26 Sep 2020 14:14:36 +0530 Subject: [PATCH 2/2] Required Changes --- LeetCode/top_k_frequent.py | 32 ++++++++++++++++++++++++++++++-- test/test_top_frequent.py | 2 +- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/LeetCode/top_k_frequent.py b/LeetCode/top_k_frequent.py index ef6b819..ed48641 100644 --- a/LeetCode/top_k_frequent.py +++ b/LeetCode/top_k_frequent.py @@ -1,19 +1,47 @@ -# Given a non-empty array of integers, return the k most frequent elements. +''' +Given a non-empty array of integers, return the k most frequent elements. + +Example 1: + +Input: nums = [1,1,1,2,2,3], k = 2 +Output: [1,2] +Example 2: + +Input: nums = [1], k = 1 +Output: [1] + +''' class Solution: - def topKFrequent(self, nums:List[int], k: int) -> List[int]: + + def topKFrequent(self, nums, k): + + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + m,v,ma={},[],0 + for i in nums: + if i in m: m[i]+=1 + else: m[i]=1 + if m[i]>ma: ma=m[i] + while k!=0: + for i in m: + if k==0: break + if m[i]==ma: v.append(i) k-=1 diff --git a/test/test_top_frequent.py b/test/test_top_frequent.py index 50dbcb3..2920dc9 100644 --- a/test/test_top_frequent.py +++ b/test/test_top_frequent.py @@ -2,7 +2,7 @@ import os sys.path.append(os.path.join(sys.path[0], '..')) from LeetCode.top_k_frequent import Solution - + def test_topk(): s = Solution() assert s.topKFrequent([1,1,1,2,2,3],2) == [1,2] \ No newline at end of file