栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leetcode刷题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode刷题

215.Top K frquent elements
  1. 这道题采用桶排序,先用unordered_map来记录每个数字出现的频次。unordered_map就是python中的字典
unordered_mapcounts;		
    int max_count = 0;
	for (const int& num : nums) {
		max_count = max(max_count, ++counts[num]);
	}
  1. 然后对桶的频次进行排序,这时候可以用一个二维矩阵来存,不过这个矩阵其实就是一个篮子。
    这里以后有时间再去看一下unordered_map和篮子在C++中的底层原理。
    比如buckets[5]存着[3,4,6],整个数组中出现5次的数为[3,4,6]。然后我们根据对频次排序的结果就可以得知前k个频次最大的数是哪几个了。
class Solution {
public:
	vectortopKFrequent(vector& nums, int k) {
		unordered_mapcounts;		
        int max_count = 0;
		for (const int& num : nums) {
			max_count = max(max_count, ++counts[num]);
		}

		vector >buckets(max_count + 1);
		for (const auto& p : counts) {
			buckets[p.second].push_back(p.first);
		}

		vector ans;
		for (int i = max_count; i >= 0 && ans.size() < k; --i) {
			for (const int& num : buckets[i]) {
				ans.push_back(num);
				if (ans.size() == k) {
					break;
				}
			}
		}
		return ans;

	}
};
451.Sort Characters By Frequency
  1. 这道题运用了桶排序的方法
class Solution {
public:
	string frequencySort(string s) {
		unordered_map counts;
		int max_count = 0;
		for (auto& str : s)
			max_count = max(max_count,++counts[str]);

		vector > buckets(max_count + 1);
		for (auto& p : counts) 
			buckets[p.second].push_back(p.first);

		string ans;
		for (int i = max_count; i >= 0; --i) {
			for (auto& str : buckets[i]) {
				for (int j = 0; j < i; j++)
					ans.push_back(str);
			}
		}
		return ans;
	}
};
  1. 贴一个看到的题解简单写法,因为创建了unorded_map之后就可以直接对string使用sort排序了。
class Solution {
public:
    string frequencySort(string s) {
        unordered_map mp;
        for(auto ch:s) mp[ch]++;
        sort(s.begin(),s.end(),[&](const char &a, const char &b){
            return mp[a]==mp[b] ? a>b : mp[a]>mp[b];
        });
        return s;
    }
};
75.Sort Colors
class Solution {
public:
    void sortColors(vector& nums) {
        map counts;
        for(auto& num : nums)
            ++counts[num];
        nums.clear();
        for (auto iter = counts.begin(); iter != counts.end();++iter)
            nums.insert(nums.end(), iter->second, iter->first);
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1004666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号