yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #274 H-Index #134

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int hIndex(int[] citations) {
        if (citations == null || citations.length == 0) {
            return 0;
        }

        int result = 0;

        Arrays.sort(citations);
        int length = citations.length;
        for (int i = length - 1; i >= 0; i--) {
            if (citations[i] >= length - i) {
                result = length - i;
                if (citations[i] == length - i) {
                    return result;
                }
            }
        }
        return result;

    }
}

My concise java solution beats 95%!

Here is some HashTable solution with lower running time, but worthy to learn: scan through the citations and maintain the h-index calculated from the scanned citations so far, mean while having a hash table to keep track of the counts of papers that are having the same citation that contributed to the current h-index. reference: https://leetcode.com/problems/h-index/discuss/70793/Java-O(n)-Hash-Table-solution-(Didn't-find-similar-idea-in-other-posts)

public class Solution {
    public int hIndex(int[] citations) {
        Map<Integer, Integer> map = new HashMap<>();
        int h = 0;
        for (int c : citations) {
            if (c > h) {
                if (map.getOrDefault(h, 0) != 0) {
                    map.put(h, map.getOrDefault(h, 0) - 1);
                } else {
                    h++;
                }
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
        }
        return h;
    }
}