leetcode maximum gap

来源:互联网 发布:怎么订购淘宝视频服务 编辑:程序博客网 时间:2024/05/21 00:45

先贴代码:

class Solution{public: /*by default, numbers in num vector is non-negative integers within 32 signed bits*/int maximumGap(vector<int> &num){int size = num.size();if(size < 2){  //if length of num is less than 2, no gapreturn 0;}vector<int> tmp;tmp.resize(size);int cnt[10];int base = 10, maxlen = -1;for(int i = 0; i < size; ++i){ /*calculate max bits of the numbers*/maxlen = max(maxlen, num[i] == 0 ? 1: (int)(log10((double)num[i])+1));}//cout << "maxlen is " << maxlen << endl;for(int i = 0; i < maxlen; ++i){ /*get the (i+1)-th digit from right and sort based on the index*/memset(cnt, 0 ,sizeof(cnt));for(int j = 0; j < size; ++j){int index = num[j] % base;index /= (base / 10);//cout << num[j] << " num[j] " << index << " index " << endl;cnt[index]++;}for(int i = 1; i < 10; ++i){cnt[i] += cnt[i-1];} for(int j = size - 1; j >= 0; --j){ /*enumerate from right to left guarantees that sort is steady*/int index = num[j] % base;index /= (base / 10);tmp[--cnt[index]] = num[j];}for(int j = 0; j < size; ++j){num[j] = tmp[j];}base *= 10;}int maxgap = -1;/*for(int i = 0; i < size; ++i){cout << num[i] << endl;}*/for(int j = 1; j < size; ++j){maxgap = max(maxgap, num[j] - num[j-1]);}return maxgap;}};


0 0
原创粉丝点击