继续刷题,H-index这道题不难,但是要理清思路,明白h值的具体含义,其中包含了很多种边界情况都要分别加以讨论,这些都体现在代码中。
分析题目:首先利用快速排序把数组排好序;然后,从后向前找到合适的h值,要注意对于边界的处理。总的来说,题目很简单,就当是练练手。
下面贴上leetcode accept的代码:
#include<stdio.h>
#include<stdlib.h>
void quicksort(int s[], int l, int r)
{
int i, j, x;
if (l < r)
{
i = l;
j = r;
x = s[i];
while (i < j)
{
while(i < j && s[j] > x) j--;
if(i < j) s[i++] = s[j];
while(i < j && s[i] < x) i++;
if(i < j) s[j--] = s[i];
}
s[i] = x;
quicksort(s, l, i-1);
quicksort(s, i+1, r);
}
}
int hIndex(int* citations, int citationsSize) {
quicksort(citations,0,citationsSize-1);
int count=0;
if(citationsSize==0) return 0;
for(int i=citationsSize-1;i>=0;i--)
{
if(citationsSize==1)
{
if(citations[0]>0)return 1;
else return 0;
}
else if(count>=citations[i])
{
return count;
}
++count;
if(count==citationsSize)
return count;
}
}