leetcode 164. Maximum Gap

来源:互联网 发布:淘宝店铺男装推荐 编辑:程序博客网 时间:2024/06/09 14:35

164. Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.


要求线性时间,只能空间换时间,用计数排序,出现过的num用map来存。
   并且在map里面会自动排序,小的在前。


class Solution {public:    int maximumGap(vector<int>& nums)     {        if (nums.size() < 2)            return 0;                   map<int,int> pp;        for (int i = 0; i < nums.size(); i++)            pp[nums[i]]++;                     int ret = 0;            int lastnum = -1;        for(auto it = pp.begin(); it != pp.end(); it++)        {            if (lastnum != -1)                ret = max(ret , (it->first - lastnum) );            lastnum = it->first;        }        return ret;    }};


原创粉丝点击