zoukankan      html  css  js  c++  java
  • 768. Max Chunks To Make Sorted II

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.


    Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

    What is the most number of chunks we could have made?

    Example 1:

    Input: arr = [5,4,3,2,1]
    Output: 1
    Explanation:
    Splitting into two or more chunks will not return the required result.
    For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
    

    Example 2:

    Input: arr = [2,1,3,4,4]
    Output: 4
    Explanation:
    We can split into two chunks, such as [2, 1], [3, 4, 4].
    However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
    

    Note:

    • arr will have length in range [1, 2000].
    • arr[i] will be an integer in range [0, 10**8].

    解题思路:

    注意一下一个空vector含两个指针,为2b,32位电脑为8B,64位为16B。这里数字是10^8用vector是放不下的!!

    1. class Solution {  
    2. public:  
    3.     int maxChunksToSorted(vector<int>& arr) {  
    4.         unordered_map<int ,int> ss;  
    5.         vector<int> temp(arr);  
    6.         sort(arr.begin(),arr.end());  
    7.         multiset<int> ret;  
    8.         unordered_map<int,vector<int>> store;  
    9.           
    10.           
    11.         for(int i=0;i<arr.size();i++){  
    12.             store[arr[i]].push_back(i);  
    13.         }  
    14.           
    15.         int max_index=-99999;int count=0;  
    16.         for(int i=0;i<temp.size();i++){  
    17.             int now_index;  
    18.             if(store[temp[i]].size()>0)  
    19.              now_index = store[temp[i]][0];  
    20.             store[temp[i]].erase(store[temp[i]].begin());  
    21.             if(now_index>max_index) max_index=now_index;  
    22.               
    23.             if(max_index==i) {count++;max_index=-99999;}  
    24.               
    25.         }  
    26.         return count;  
    27.     }  
    28. };  
  • 相关阅读:
    常见的兼容问题
    清除浮动
    简单的容器盒子
    查找并替换中文字符
    遍历对象属性值
    统一服务器和界面的传输格式
    随机生成包含大小写和数字的字符串
    网站翻译功能
    菜鸟安装vue-devtool 工具
    安装虚拟机所遇到的问题
  • 原文地址:https://www.cnblogs.com/liangyc/p/8849043.html
Copyright © 2011-2022 走看看