LeetCode:H-Index、H-Index II - H指數

一、題目名稱java

H-Index(H指數)數組

二、題目地址函數

https://leetcode.com/problems/h-index/code

三、題目內容排序

英文: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.ip

中文:給出一個數組記錄一個研究者各篇文章的引用數,寫一個函數計算這個研究者的H指數ci

四、解題方法leetcode

H指數是一個2005年由Jorge E. Hirsch提出的用於評估研究人員的學術產出數量與學術產出水平的指標。更詳細的信息能夠參考h-index的維基百科頁面。實現H指數的計算方法能夠從它的定義入手,即一我的在其全部學術文章中有N篇論文分別被引用了至少N次,他的H指數就是N。開發

一段實現此方法的Java代碼以下:get

/**
 * 功能說明:LeetCode 275 - H-Index
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月10日
 */
public class Solution {
    
    /**
     * 求文獻引用的H指數
     * @param citations 引用次數
     * @return H指數
     */
    public int hIndex(int[] citations) {
        
        if (citations.length == 0) {
            return 0;
        }

        //數組元素降序排列
        int temp;
        for (int i = 0; i < citations.length; i++) {
            for (int j = i + 1; j < citations.length; j++) {
                if (citations[i] < citations[j]) {
                    temp = citations[i];
                    citations[i] = citations[j];
                    citations[j] = temp;
                }
            }
        }
        
        //計算H指數
        int result = 0;
        for (Integer cites : citations) {
            if (result >= cites) {
                return result;
            }
            result++;
        }
        
        return result;
    }
}

使用Arrays.sort函數進行排序能夠加快計算速度,不過Arrays.sort排序後是升序,因此要用反方向遍歷數組:

import java.util.Arrays;

/**
 * 功能說明:LeetCode 275 - H-Index
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月10日
 */
public class Solution {
    
    /**
     * 求文獻引用的H指數
     * @param citations 引用次數
     * @return H指數
     */
    public int hIndex(int[] citations) {
        
        if (citations.length == 0) {
            return 0;
        }

        //數組元素降序排列
        Arrays.sort(citations);
        
        //計算H指數
        int result = 0;
        for (int i = citations.length - 1; i >= 0; i--) {
            if (result >= citations[i]) {
                return result;
            }
            result++;
        }
        
        return result;
    }
}

若是數組很長,在排序完畢後也能夠試着採用二分查找法計算H指數。

四、275題解題方法

第275題名稱:H-Index II(H指數-2)

第275題地址:https://leetcode.com/problems/h-index-ii/

第275題的內容與第274題基本一致,只是多提供了一個條件:傳入的數組是升序排列的。這道題仍然能夠使用上面的方法計算H指數,不過能夠省略對數組進行手工排序的步驟。

import java.util.Arrays;

/**
 * 功能說明:LeetCode 275 - H-Index
 * 開發人員:Tsybius2014
 * 開發時間:2015年9月10日
 */
public class Solution {
    
    /**
     * 求文獻引用的H指數
     * @param citations 引用次數
     * @return H指數
     */
    public int hIndex(int[] citations) {
        
        if (citations.length == 0) {
            return 0;
        }

        //計算H指數
        int result = 0;
        for (int i = citations.length - 1; i >= 0; i--) {
            if (result >= citations[i]) {
                return result;
            }
            result++;
        }
        
        return result;
    }
}

END

相關文章
相關標籤/搜索