zoukankan      html  css  js  c++  java
  • No.164 Maximum Gap

    No.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.

    题意理解:successive连续的
         输入:未排序数组,数组元素均为非负整数,在32位整数范围内
        输出:输出排序后连续元素的最大差值
        要求:线性时间/空间
    法一:直观做法就是排序,之后一次比较,但时间空间效率不高!!!

     1 class Solution
     2 {
     3 public:
     4     int    maximumGap(vector<int> &nums)
     5     {//题意理解:successive连续的
     6      //输入:未排序数组,数组元素均为非负整数,在32位整数范围内
     7      //输出:输出排序后连续元素的最大差值
     8      //要求:线性时间/空间
     9      //直观做法就是排序,之后一次比较,但时间空间效率不高!!!
    10         int count = nums.size();
    11         if(count <2)
    12             return 0;
    13         sort(nums.begin(),nums.end());
    14         int maxGap = nums[1] - nums[0];
    15 
    16         for(int i=2; i<count; i++)
    17         {
    18             if(maxGap < nums[i]-nums[i-1])
    19                 maxGap = nums[i]-nums[i-1];
    20         }
    21         return maxGap;
    22     }
    23 };
    View Code


    法二:

    官方提示: 表示没有理解!!!

    Suppose there are N elements and they range from A to B.

    Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

    Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

    for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

    Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

    For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

     

    参考:http://www.cnblogs.com/ganganloveu/p/4162290.html

  • 相关阅读:
    json转MAP
    责任链模式
    单例模式
    代理模式
    策略模式
    mysql触发器的使用
    Java 中的日期和时间
    MySQL插入数据前检测唯一性
    java字符串转为Map类型:split()方法的应用
    java Socket实例
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4561438.html
Copyright © 2011-2022 走看看