zoukankan      html  css  js  c++  java
  • 112th LeetCode Weekly Contest Minimum Increment to Make Array Unique

    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:

    1. 0 <= A.length <= 40000
    2. 0 <= A[i] < 40000

    问的是把数组的数字+1,几次后,数组的数字唯一了。

    这里有个解法,把重复的拿出来,从小到大排序。从[min,max](max不一定就是代码的那个),哪个位置缺了就填哪个,然后算sum +=(i-ans);

    其实优雅的解法应该是第二个

    class Solution {
    public:
        int minIncrementForUnique(vector<int>& A) {
            int sum = 0;
            int ans = 0;
            int pos = 0;
            int Min = 40000;
            map<int,int> mp;
            stack<int>st;
            vector<int>ve;
            for(int i=0;i<A.size();i++){
                Min = min(Min,A[i]);
                mp[A[i]]++;
                
                if(mp[A[i]]>=2){
                    ve.push_back(A[i]);
                }
            }
            sort(ve.begin(),ve.end());
            for(int i=ve.size()-1;i>=0;i--){
                st.push(ve[i]);
            }
            for(int i=0;i<400000;i++){
                if(st.empty()){
                    break;
                }
                if(mp[i]==0){
                    ans = st.top();
                    if(i<ans){
                        continue;
                    }
                    sum +=(i-ans);
                    st.pop();
                    mp[i]=1;
                }
            }
            return sum;
        }
    };
    class Solution {
    public:
        int minIncrementForUnique(vector<int>& A) {
            sort(A.begin(), A.end());
            int lowest = -1, total = 0;
    
            for (int a : A) {
                lowest = max(lowest, a);
                total += lowest - a;
                lowest++;
            }
    
            return total;
        }
    };
  • 相关阅读:
    多点触摸的一些代码
    精灵跳跃练习
    svn安装所遇到的几个问题[转载]
    简易包边字画法
    http和socket简介
    ant使用笔记
    j2se图片拖拽练习
    A星寻路示例
    迅为瑞芯微iTOP3399开发板资料更新
    迅为i.MX6Q开发板NXP恩智浦ARM安卓linux开发板
  • 原文地址:https://www.cnblogs.com/yinghualuowu/p/10020188.html
Copyright © 2011-2022 走看看