Leetcode-maximum Gap

Source: Internet
Author: User

Maximum Gap

2015.1.23 15:00

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.

Assume all elements in the array is non-negative integers and fit in the 32-bit signed integer range.


This are not a O (n) solution, but O (n * log (n)). Sort the array and find the maximal gap.

As for a linear solution, I ' m searching for it ...

Discussions Online said it could be solved using the bucket sort, but the doesn ' t really satisfy O (n) time scale, right? At least I wouldn ' t take it for O (n).

Accepted Code:

1 //1AC, not a O (n) solution, though, one not yet come ...2#include <algorithm>3 using namespacestd;4 5 classSolution {6  Public:7     intMaximumgap (vector<int> &num) {8 sort (Num.begin (), Num.end ());9         intN;Ten          Onen = (int) num.size (); A         if(N <2) { -             return 0; -         } the          -         inti; -         intAns = ABS (num[0]-num[1]); -          for(i =2; I < n; ++i) { +ans = max (ans, ABS (Num[i-1] -num[i])); -         } +          A         returnans; at     } - Private: -     intMaxConst int&x,Const int&y) { -         returnx > y?x:y; -     } -      in     intAbsConst int&x) { -         returnX >=0? X:-x; to     } +};

Leetcode-maximum Gap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.