• Maximum Gap


    Total Accepted: 26010 Total Submissions: 102064 Difficulty: 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.

    /*
    n 个数,n-1个桶
    1,2,3,4,5,7 7-1/5=1.2; 1,2.2) 2.2,3.4) 3.4,4.6) 4.6,5.8) 5.8,7 2 3 4 5 7 */ class Solution { public: int maximumGap(vector<int>& nums) { int nums_size = nums.size(); int nums_min = nums_size==0 ? 0 : *min_element(nums.begin(),nums.end()); int nums_max = nums_size==0 ? 0 : *max_element(nums.begin(),nums.end()); if(nums_size <= 2){ return nums_max-nums_min; } if(nums_max-nums_min<=1){ return nums_max-nums_min; } vector<int> bucket_max(nums_size,INT_MIN); vector<int> bucket_min(nums_size,INT_MAX); double bucket_gap = (nums_max-nums_min)*1.0/(nums_size-1); for(int i=0;i<nums_size;i++){ int pos = floor((nums[i] - nums_min)/bucket_gap); bucket_max[pos] = max(bucket_max[pos],nums[i]); bucket_min[pos] = min(bucket_min[pos],nums[i]); } int max_gap = 0 ,pre_bucket_max =bucket_max[0] ; for(int i= 1;i<nums_size;i++){ if(bucket_min[i]==INT_MAX) continue; max_gap = max ( bucket_min[i]-pre_bucket_max,max_gap); pre_bucket_max = bucket_max[i]; } return max_gap; } }; //[1,3,4,65,34,2]
  • 相关阅读:
    事件
    DOM中对象的获得
    C# 字符串 相关操作
    两个listbox 复制
    C#窗体控件简介ListBox
    store procedure
    view_baseInfo
    不走弯路,就是捷径
    inherit
    Excel 版本对应
  • 原文地址:https://www.cnblogs.com/zengzy/p/5049509.html
Copyright © 2020-2023  润新知