LeetCode: H-Index

LeetCode: H-Index

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher’s h-index.

According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.

Example 1:

Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] 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, their h-index is 3.

Example 2:

Input: citations = [1,3,1]
Output: 1

Constraints:

  • n == citations.length
  • 1 <= n <= 5000
  • 0 <= citations[i] <= 1000

Version 1

public class Solution {
        public int HIndex(int[] citations)
    {
       var length = citations.Length;

        var index = 0;
        for (int i = 1; i <= length ; i++)
        {
            var count = citations.Count(a=>a>=i);
            if (count >= i && i > index)
                index = i;
        }

        return index;
    }

}

//testing Code
    H_Index _indexer = new H_Index();

    [Test]
    public void Test001()
    {
        _indexer.HIndex(new int []{3, 0, 6, 1, 5}).Should().Be(3);
    }
    
    [Test]
    public void Test002()
    {
        _indexer.HIndex(new int []{1, 3, 1}).Should().Be(1);
    }

直覺的思路在一開始我確實沒有看理解,所以一直沒看準一個原則就是h值必須同時要在陣列中找到至少 >= h值有h個項目。這兩個必須相等,一開始我還以為是要找出符合hindex的陣列位置。

送出後一看不得了,笑死,這複雜度是O(N2),而且以提交結果才beat 5.74%,代表一定要再想辦法優化了

第二版本

其實簡化計算規則,就是先排序由大到小,然後比對若>指數,就指數累加(=不累加)

var sorted = citations.OrderByDescending(a=>a).ToArray();

var h = 0;
foreach (var value in sorted)
{
if (value > h)
h++;
}

return h;

這個版本是Linq 對int[]的排序是O(n log n)

看看其他人的版本改寫如下(beat 95%)

C#陣列預設排序為 快速排序,也是O(nlogn),再走訪一次n個迴圈是O(n),表示方式為 O(n log n + n )直接呈現O(n log n),因為由大到小,所以一旦比對不符合就可以break掉

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *