[leetcode]-164. Maximum Gap

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

Return 0 if the array contains less than 2 elements.

Example 1:

Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
             (3,6) or (6,9) has the maximum difference 3.

Example 2:

Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

Note:

  • You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
  • Try to solve it in linear time/space.

代码如下:

int maximumGap(int* nums, int numsSize) {
    if(numsSize<2)
        return 0;
    int i,j,k,tem,gap;
    for(i=0;i<numsSize-1;i++)
    {
        k=i;
        for(j=i+1;j<numsSize;j++)
        {
            if(nums[k]>nums[j])
                k=j;
        }
        if(i!=k)
        {
           tem=nums[i];
           nums[i]=nums[k];
           nums[k]=tem;
        }
    }
    gap=nums[1]-nums[0];
    for(j=2;j<numsSize;j++)
    {
        tem=nums[j]-nums[j-1];
        if(tem>gap)
            gap=tem;
    }
    return gap;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/81432190
GAP
GAP
今日推荐