当前位置:网站首页>【1331. 数组序号转换】
【1331. 数组序号转换】
2022-07-28 18:43:00 【千北@】
来源:力扣(LeetCode)
描述:
给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。
序号代表了一个元素有多大。序号编号的规则如下:
- 序号从 1 开始编号。
- 一个元素越大,那么序号越大。如果两个元素相等,那么它们的序号相同。
- 每个数字的序号都应该尽可能地小。
示例 1:
输入:arr = [40,10,20,30]
输出:[4,1,2,3]
解释:40 是最大的元素。 10 是最小的元素。 20 是第二小的数字。 30 是第三小的数字。
示例 2:
输入:arr = [100,100,100]
输出:[1,1,1]
解释:所有元素有相同的序号。
示例 3:
输入:arr = [37,12,28,9,100,56,80,5,12]
输出:[5,3,4,2,8,6,7,1,3]
提示:
- 0 <= arr.length <= 105
- -109 <= arr[i] <= 109
方法:排序 + 哈希表
思路
首先用一个数组保存排序完的原数组,然后用一个哈希表保存各元素的序号,最后将原属组的元素替换为序号后返回。
代码:
class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
vector<int> sortedArr = arr;
sort(sortedArr.begin(), sortedArr.end());
unordered_map<int, int> ranks;
vector<int> ans(arr.size());
for (auto &a : sortedArr) {
if (!ranks.count(a)) {
ranks[a] = ranks.size() + 1;
}
}
for (int i = 0; i < arr.size(); i++) {
ans[i] = ranks[arr[i]];
}
return ans;
}
};
执行用时:100 ms, 在所有 C++ 提交中击败了39.83%的用户
内存消耗:38.3 MB,在所有 C++ 提交中击败了46.48%的用户
复杂度分析
时间复杂度:O(n × logn),其中 n 是输入数组 arr 的长度,排序消耗O(n × logn) 时间。
空间复杂度:O(n)。有序数组和哈希表各消耗O(n) 空间。
arthor:LeetCode-Solution
边栏推荐
- Speech controlled robot based on ROS (I): realization of basic functions
- 太空射击第13课: 爆炸效果
- Want to draw a picture that belongs to you? AI painting, you can also
- The engineering practice of super large model was polished, and Baidu AI Cloud released the cloud native AI 2.0 solution
- Unity typewriter teaches you three ways
- Mongoose condition queries the data of a certain time period
- Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
- Raspberry pie uses the command line to configure WiFi connections
- 关于正则的两道笔试面试题
- Redis入门二:redhat 6.5安装使用
猜你喜欢
![[detailed use of doccano data annotation]](/img/40/c18cf8d5519328d707ed89fccb70ee.png)
[detailed use of doccano data annotation]

How to balance security and performance in SQL?

Raspberry pie 4B deploy yolov5 Lite using ncnn

Explain RESNET residual network in detail

【pytorch】LSTM神经网络

如何平衡SQL中的安全与性能?

Residual network RESNET source code analysis - pytoch version

Torch. NN. Linear() function

Want to draw a picture that belongs to you? AI painting, you can also

NAT实验演示(Huawei交换机设备配置)
随机推荐
卡通js射击小游戏源码
动态规划:背包问题模板代码汇总
h5微信射击小游戏源码
Use of DDR3 (axi4) in Xilinx vivado (3) module packaging
Unity uses shader to quickly make a circular mask
企业如何成功完成云迁移?
[detailed use of doccano data annotation]
One article makes you understand what typescript is
Representation of base and number 2
超大模型工程化实践打磨,百度智能云发布云原生AI 2.0方案
C# 委托 delegate 的理解
#yyds干货盘点# 面试必刷TOP101:链表中的节点每k个一组翻转
Want to draw a picture that belongs to you? AI painting, you can also
FPGA programming experience
Torch. NN. Linear() function
太空射击第09课:精灵动画
js飞入js特效弹窗登录框
js可拖拽alert弹窗插件
MySQL batch update data
[link url]