week12-leetcode #347-Top-K-Frequent-Elements

来源:互联网 发布:雕刻机制图软件 编辑:程序博客网 时间:2024/05/24 02:48

week12-leetcode #347-Top-K-Frequent-Elements

链接:https://leetcode.com/problems/top-k-frequent-elements/description/

Question

Given a non-empty array of integers, return the k most frequent elements.

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.

Solution

time complecity: O(nlogn)

class Solution {public:  struct cmpByValue {    bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {      return lhs.second > rhs.second;    }  };  vector<int> topKFrequent(vector<int>& nums, int k) {    map<int, int> my_map;    for (int i = 0; i < nums.size(); i++) {      if (my_map.find(nums[i]) != my_map.end()) {        my_map[nums[i]]++;      } else {        my_map[nums[i]] = 1;      }    }    vector<pair<int, int> > my_map_vec(my_map.begin(), my_map.end());    std::sort(my_map_vec.begin(), my_map_vec.end(), cmpByValue());    vector<int> result;    int index = 0;    for (auto iter = my_map_vec.begin(); iter != my_map_vec.end(); iter++) {      result.push_back(iter->first);      index++;      if (index == k)        break;    }    return result;  }};

思路:对输入的数组构建一个词频映射map(每一项是(num, frequence)),然后对映射形成的(num, frequence)按照frequence进行从大到小排序,最后将map每一项的第一个元素num加入到结果向量中。整个过程在对frequence排序的时候复杂度较高,为nlogn

原创粉丝点击