程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode--H-Index

LeetCode--H-Index

編輯:C++入門知識

LeetCode--H-Index


題目描述:
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.


本題是說,對於一個數組arr中的每一個數arr[i],其中i∈[0,n-1] ,找到元素個數k,其中0

思路:
對於數組arr,如果進行倒序排序再遍歷的話,對於i和arr[i]關系,由於i是遞增的,而arr[i]遞減,只要找到第一個i>=arr[i],那麼後面第n-i個元素一定滿足i>=arr[i]。因此,在遍歷過程中,只要統計所有滿足i

因此本題可以轉換為:對數組arr進行倒序排序,統計index < arr[index]的個數。例如對於


3,5,7,1,2,3來說,排序後為: 7,5,3,3,2,1
0 < 7 => count ++
1 < 5 => count ++
2 < 3 => count ++
3 = 3
4 > 2
5 > 1


因此H-index 為count = 3



實現代碼:

public class Solution {
    public int HIndex(int[] citations) {
            if(citations.Length == 0){
        		return 0;
        	}
        
           var sorted = citations.OrderByDescending(x=>x).ToList();
           var sum = 0;
           for(var i = 0;i < sorted.Count; i++){
               if(i < sorted[i]){
        	   		sum ++;
        	   }
           }
           
           return sum;
    }
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved