# 275. H-Index II (1)

[Link](https://leetcode.com/problems/h-index-ii/description/)

Given an array of citations **sorted in ascending order** (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](https://en.wikipedia.org/wiki/H-index): "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."

**Example:**

```
Input: citations = [0,1,3,5,6]
Output: 3 
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 
             received 0, 1, 3, 5, 6 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, her h-index is 3.
```

**Note:**

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

**Follow up:**

* This is a follow up problem to [H-Index](https://leetcode.com/problems/h-index/description/), where `citations` is now guaranteed to be sorted in ascending order.
* Could you solve it in logarithmic time complexity?

**Solution**

透過binary search去解決找出citation\[i] >= len - i

```
public static int hIndex2(int[] citations){
        Arrays.sort(citations);
        for(int i = 0; i < citations.length; i++){
            if(citations[i] >= (citations.length - i)){
                return citations.length - i;
            }
        }
        return 0;
    }
```

將問題簡化成用有該citation以上的paper數當作index

ex:  &#x20;

citations             \[0 1 3 5 6]\
原index                0 1 2 3 4\
new index            5 4 3 2 1

然後從頭開始找當第一個new index >= citation時，new index就是那個 h (binary search)

**要記住iteration結束後，left一定會指向造成h-index的位置，可以用len - left取得H value**

```
  public int hIndex(int[] citations) {
        int len = citations.length;
        int paperWithMoreCitationCount;
        int left = 0;
        int right = paperCount-1;
        int mid;
        while(right >= left){
            mid = (left + right) /2 ;
            paperWithMoreCitationCount = len - mid;
            if(paperWithMoreCitationCount == citations[mid]){
                return paperWithMoreCitationCount;
            }
            else if(paperWithMoreCitationCount > citations[mid]) {
                //mid有可能是對的，但可以往右看看是否有更高的
                left = mid+1;
            }
            else{
                right = mid-1;
            }
        }
        return paperCount - left;
        //end the loop, the left will point the index that create h-index

    }

```
