H-Index I & II

H-Index I

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."

For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.

Note: If there are several possible values for h, the maximum one is taken as the h-index.

分析:

先排序,然后看倒数第n个的paper它的citation是否超过n.

 1 public class Solution {
 2     public int hIndex(int[] citations) {
 3         // 排序
 4         Arrays.sort(citations);
 5         int h = 0;
 6         for(int i = 1; i <= citations.length; i++){
 7             // 最后i个paper的最小index是否大于i
 8             if (citations[citations.length - i] >= i) {
 9                 h = Math.max(h, i);
10             }
11         }
12         return h;
13     }
14 }

H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

 1 public class Solution {
 2     public int hIndex(int[] citations) {
 3         int start = 0;
 4         int end = citations.length - 1;
 5         
 6         while (start <= end) {
 7             int mid = (start + end) / 2;
 8             if (citations[mid] >= citations.length - mid) {
 9                 end = mid - 1;
10             } else {
11                 start = mid + 1;
12             }
13         }
14         return citations.length - start;
15     }
16 }

 

posted @ 2016-08-05 11:06  北叶青藤  阅读(198)  评论(0)    收藏  举报