diff --git a/README.md b/README.md index 16acd1391..9362904c5 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ LeetCode | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | +|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium| |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp)|Medium| diff --git a/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp b/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp new file mode 100644 index 000000000..245c3ba0b --- /dev/null +++ b/algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp @@ -0,0 +1,65 @@ +// Source : https://leetcode.com/problems/top-k-frequent-elements/ +// Author : Calinescu Valentin +// Date : 2016-05-02 + +/*************************************************************************************** + * + * Given a non-empty array of integers, return the k most frequent elements. + * + * For example, + * Given [1,1,1,2,2,3] and k = 2, return [1,2]. + * + * Note: + * You may assume k is always valid, 1 ≤ k ≤ number of unique elements. + * Your algorithm's time complexity must be better than O(n log n), where n is the + * array's size. + * + ***************************************************************************************/ + +class Solution { +public: + struct element//structure consisting of every distinct number in the vector, + //along with its frequency + { + int number, frequency; + bool operator < (const element arg) const + { + return frequency < arg.frequency; + } + }; + priority_queue sol;//we use a heap so we have all of the elements sorted + //by their frequency + vector solution; + + vector topKFrequent(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int i = 1; + for(; i < nums.size(); i++) + { + int freq = 1; + while(i < nums.size() && nums[i] == nums[i - 1]) + { + i++; + freq++; + } + element el; + el.number = nums[i - 1]; + el.frequency = freq; + sol.push(el); + } + if(i == nums.size())//if we have 1 distinct element as the last + { + element el; + el.number = nums[nums.size() - 1]; + el.frequency = 1; + sol.push(el); + } + while(k)//we extract the first k elements from the heap + { + solution.push_back(sol.top().number); + sol.pop(); + k--; + } + return solution; + } +};