• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
164. Maximum Gap *HARD* -- 无序数组找出排序后连续元素的最大间隔

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.

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        int n = nums.size(), mini, maxi, i, j, k, prev = -1, ans = 0;
        if(n < 2)
            return 0;
        mini = maxi = nums[0];
        for(i = 1; i < n; i++)
        {
            if(nums[i] < mini)
                mini = nums[i];
            if(nums[i] > maxi)
                maxi = nums[i];
        }
        k = (maxi - mini) / n + 1;
        vector<vector<int>> v(n);
        for(i = 0; i < n; i++)
        {
            j = (nums[i] - mini) / k;
            if(0 == v[j].size())
            {
                v[j].push_back(nums[i]);
                v[j].push_back(nums[i]);
            }
            else
            {
                v[j][0] = max(nums[i], v[j][0]);
                v[j][1] = min(nums[i], v[j][1]);
            }
        }
        for(i = 0; i < n; i++)
        {
            if(0 == v[i].size())
                continue;
            if(prev != -1)
            {
                j = v[i][1] - v[prev][0];
                ans = max(ans, j);
            }
            prev = i;
        }
        return ans;
    }
};

将nums分为n组,每组k = (maxi - mini) / n + 1个数,分别求出每组的最大值和最小值。

posted on 2016-08-22 18:07  ArgenBarbie  阅读(296)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3