当前位置:网站首页>leetcode_1365
leetcode_1365
2022-06-24 19:25:00 【programing菜鸟】
:法一
利用条件每个nums[i] <= 100,可以创建一个101空间的频率数组,利用计数排序算出每个数字出现的频率。然后小于当前数字的数字个数就是频率数组中以该数字为下标的前面的所有项数和。
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> cnt(101);
for(int e : nums){
//频率数组
cnt[e]++;
}
int sum = 0;
vector<int> smallerThatVector(101);
for(int i = 0; i < 101; ++i){
smallerThatVector[i] += sum; //搞出一个前几项和数组
sum += cnt[i];
}
for(int i = 0; i < nums.size(); ++i){
nums[i] = smallerThatVector[nums[i]]; //和数组的项就是答案
}
return nums;
}
};
法二:
利用map的自动排序。创建一棵map,key是int,value是vector。将nums[i]中的每个元素插入map中,且将nums[i]的下表插入对应的vector中。这样再遍历一遍map,ans数组的对应项就是map中的vector前几项的size和。
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
map<int, vector<int>> cnt; //每错,map的value是vector<int>
for(int i = 0; i < nums.size(); ++i){
cnt[nums[i]].push_back(i); //将nums[i]全部insert进入map
} //且将nums[i]对应的下标插入对应的vector<int>
vector<int> ans(nums.size()); //结果数组
int sum = 0;
for(auto it = cnt.begin(); it != cnt.end(); ++it){
int size = (it->second).size();
for(int i = 0; i < size; ++i){
int index = (it->second)[i]; //拿到vector<int>的值,也就是该
ans[index] = sum; //key在原数组对应的下标。
}
sum += (it->second).size(); //sum就是所有小于当前key的个数和
}
return ans;
}
};
边栏推荐
- 使用Adb连接设备时提示设备无权限
- Please open online PDF carefully
- 【产品设计研发协作工具】上海道宁为您提供蓝湖介绍、下载、试用、教程
- Why are life science enterprises on the cloud in succession?
- [cloud native learning notes] kubernetes practice command
- 虚拟机CentOS7中无图形界面安装Oracle(保姆级安装)
- 123. the best time to buy and sell shares III
- how to install clustershell
- 直击“三夏”生产:丰收喜报频传 夏播紧锣密鼓
- Call process of package receiving function
猜你喜欢

虚拟货币7个月蒸发2万亿美元,“马斯克们”终结15万人暴富梦

【Camera基础(一)】Camera摄像头工作原理及整机架构

Alibaba cloud lightweight servers open designated ports

介绍BootLoader、PM、kernel和系统开机的总体流程

Pattern recognition - 1 Bayesian decision theory_ P1

使用 Go 编程语言 66 个陷阱:Golang 开发者的陷阱和常见错误指北

ping: www.baidu.com: 未知的名称或服务

大厂出海,败于“姿态”

Multi view function in blender

EditText controls the soft keyboard to search
随机推荐
Web project deployment
TCP specifies the source port
Unity关于本地坐标和世界坐标之间的转换
力扣每日一题-第26天-496.下一个更大元素Ⅰ
[product design and R & D collaboration tool] Shanghai daoning provides you with blue lake introduction, download, trial and tutorial
Volcano成Spark默认batch调度器
[cloud native learning notes] kubernetes Foundation
Antdb database online training has started! More flexible, professional and rich
【产品设计研发协作工具】上海道宁为您提供蓝湖介绍、下载、试用、教程
Wireshark packet capturing skills summarized by myself
The most important thing at present
Minimum cost and maximum flow (template question)
Tso hardware sharding is a header copy problem
Address mapping of virtual memory paging mechanism
MySQL optimizes query speed
188. 买卖股票的最佳时机 IV
Page replacement of virtual memory paging mechanism
多路转接select
how to install clustershell
Memcached comprehensive analysis – 2 Understand memcached memory storage