112th LeetCode Weekly Contest Minimum Increment to Make Array Unique
2024-09-03 19:14:46
Given an array of integers A, a move consists of choosing any A[i]
, and incrementing it by 1
.
Return the least number of moves to make every value in A
unique.
Example 1:
Input: [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: [3,2,1,2,1,7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
Note:
0 <= A.length <= 40000
0 <= A[i] < 40000
问的是把数组的数字+1,几次后,数组的数字唯一了。
这里有个解法,把重复的拿出来,从小到大排序。从[min,max](max不一定就是代码的那个),哪个位置缺了就填哪个,然后算sum +=(i-ans);
其实优雅的解法应该是第二个
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
int sum = ;
int ans = ;
int pos = ;
int Min = ;
map<int,int> mp;
stack<int>st;
vector<int>ve;
for(int i=;i<A.size();i++){
Min = min(Min,A[i]);
mp[A[i]]++; if(mp[A[i]]>=){
ve.push_back(A[i]);
}
}
sort(ve.begin(),ve.end());
for(int i=ve.size()-;i>=;i--){
st.push(ve[i]);
}
for(int i=;i<;i++){
if(st.empty()){
break;
}
if(mp[i]==){
ans = st.top();
if(i<ans){
continue;
}
sum +=(i-ans);
st.pop();
mp[i]=;
}
}
return sum;
}
};
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
sort(A.begin(), A.end());
int lowest = -, total = ; for (int a : A) {
lowest = max(lowest, a);
total += lowest - a;
lowest++;
} return total;
}
};
最新文章
- zTree和SweetAlert插件初探
- ListView的联动实现
- 年终汇报、总结、述职:教你做一场B格满满的技术大会演讲
- git和github使用方式
- log4net 部署到服务器之后 无法记录日志问题 解决方法
- <;转>;MySql 与Oracle区别
- 首页的sitecontent地址
- 常见maven镜像
- csdn如何转载别人的文章
- Ajax beforeSend和complete 方法
- Java实现单链表的快速排序和归并排序
- [物理学与PDEs]第1章习题12 Coulomb 规范下电磁场的标势、矢势满足的方程
- openstack swift 安装(单独对象存储服务)
- 背水一战 Windows 10 (122) - 其它: 通过 Windows.System.Profile 命名空间下的类获取信息, 查找指定类或接口的所在程序集的所有子类和子接口
- Openssl与私有CA搭建
- linux scp传输文件命令
- Wireshark 分析捕获的数据记录
- numpy库中的知识点&mdash;&mdash;积累
- 【BZOJ1692】[Usaco2007 Dec]队列变换 后缀数组+贪心
- 使用Xib创建自定义视图(不是cell)时需要注意的问题
热门文章
- oralce错误总结
- El表达式 (先大致的记录下吧!以后慢慢深入)
- dev初识 拖动分组
- mysql for visual
- The user specified as a definer (”@sa’%&#39;) does not exist 解决方法
- 2.8.3 并发下诡异的HashMap
- Linux下的fdlisk - l 用法解析-入门篇
- 二度Xml<;2>;
- 解决Spring Boot(2.1.3.RELEASE)整合spring-data-elasticsearch3.1.5.RELEASE报NoNodeAvailableException[None of the configured nodes are available
- jquery中attr和prop的区别(转)