先看第一题 array unsorted
我自己想到的方法是先排序 然后从后面开始找 找到一个数字<它对应的id 就应该返回它上一个数字 具体的id怎样算 见代码 o(nlogn) 时间 o(1)空间
index 0 1 2 3 4
number 0 1 3 5 6
id 5 4 3 2 1
public class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
for ( int i = citations.length - 1; i >= 0; i --){
if ( citations[i] < citations.length - i )
return citations.length - i - 1;
}
return citations.length;
}
}
答案中有一个o(n)时间 o(n)空间的
记录一个计数数组 然后从计数数组后面开始累加
public class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
int [] arr = new int [n + 1];
for ( int i = 0; i < n; i ++ ){
if ( citations[i] >= n )
arr[ n ] ++;
else
arr[ citations[i] ] ++;
}
int addUp = 0;
for ( int i = n; i >= 0; i -- ){
addUp += arr[ i ];
if ( addUp >= i )
return i;
}
return 0;
}
}
然后第二题就是给出了sorted array 用binary search更好!!!o(lgn)!!!