o(n)现在水平不够。
采用先快排序,再找。O(nlogn),注意每次划分枢纽选择中间节点(中间节点和首节点互换)
int divide(int* nums,int head,int tail){
int x=nums[(head+tail)/2];
nums[(head+tail)/2]=nums[head];
nums[head]=x;
int t=nums[head];
while(head <tail){
while(head <tail && nums[tail] > t) tail--;
if(head <tail) nums[head++]=nums[tail];
while(head < tail && nums[head] < t) head++;
if(head <tail) nums[tail--]=nums[head];
}
nums[head]=t;
return head;
}
void quicksort(int* nums,int head,int tail){
if(head >= tail) return ;
int t=divide(nums,head,tail);
if(t>head) quicksort(nums,head,t-1);
if(t<tail) quicksort(nums,t+1,tail);
}
int longestConsecutive(int* nums, int numsSize) {
if(numsSize==0) return 0;
quicksort(nums,0,numsSize-1);
int max=1;
int now=1;
for(int i=0;i<numsSize-1;i++){
if(nums[i+1]==nums[i]){
continue;
}
if(nums[i+1]-nums[i]==1){
now++;
if(now >max) max=now;
}else{
now=1;
}
}
return max;
}
结果:
标签:head,divide,nums,int,节点,序列,tail,128,最长 From: https://www.cnblogs.com/llllmz/p/18026109