码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode H-Index

时间:2015-10-28 09:32:07      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/h-index/

两种方法,第一种方法是sorting, 根据定义。6,5,3,1,0 有1篇文章引用大于等于6次,有2篇文章引用大于等于5次,有三篇文章引用大于等于3次。持续更新res. 有四篇文章引用大于等于1次, 不更新res. 最后返回res. Time Complexity O(nlogn). Space O(1).

第二种方法是用空间换时间,count[i] 存储 被引用了i遍的文章有几个,最后total的含义就是总共有几篇文章引用次数大于等于i. 引用次数大于等于 len的都算在 count[len]里面。

Time Complexity is O(n), Space O(n).

AC Java:

 1 public class Solution {
 2     public int hIndex(int[] citations) {
 3         /*
 4         //Method 1
 5         if(citations == null || citations.length == 0){
 6             return 0;
 7         }
 8         Arrays.sort(citations);
 9         int res = 0;
10         for(int i = citations.length-1; i>=0; i--){
11             if(citations[i] >= citations.length-i){
12                 res = citations.length-i;
13             }
14         }
15         return res;
16         */
17         
18         //Method 2
19         if(citations == null || citations.length == 0){
20             return 0;
21         }
22         int len = citations.length;
23         //count 数组储存了被引用 i 遍的文章有几个,i是count的index
24         int [] count = new int[len+1];
25         for(int i = citations.length - 1; i>=0; i--){
26             if(citations[i]>=citations.length){
27                 count[len]++;
28             }else{
29                 count[citations[i]]++;
30             }
31         }
32         //total 计数总共有几篇文章引用大于等于i次,i是count 的index
33         int total = 0;
34         for(int i = len; i>=0; i--){
35             total += count[i];
36             if(total>=i){ //有三篇文章引用大于等于三次
37                 return i;
38             }
39         }
40         return 0;
41     }
42 }

 

LeetCode H-Index

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4916312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!