Home [Algorithm] Sort2
Post
Cancel

[Algorithm] Sort2

Sort


Task

2. H-Index in Programmers (Level 2)


๐Ÿ“Œ Problem

https://programmers.co.kr/learn/courses/30/lessons/42747

๐Ÿ“Œ Answer

1. Use Arrays.sort()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Arrays;

class Solution {
    public int solution(int[] citations) {
        int answer = 0;

        Arrays.sort(citations);
        
        for (int i = 0; i < citations.length; i++) {
            int h = citations.length - i; // from last
            
            if (citations[i] >= h) {
                answer = h;
                break;
            }
        }
   
        return answer;
    }
}
/**
[Question]
- ๋…ผ๋ฌธ nํŽธ (1 <= n <= 1000)
    -> h๋ฒˆ ์ด์ƒ ์ธ์šฉ๋œ ๋…ผ๋ฌธ = hํŽธ ์ด์ƒ : h <= n (0 <= h <= 10000)
    -> ๋‚˜๋จธ์ง€ ๋…ผ๋ฌธ(h๋ฒˆ ์ดํ•˜ ์ธ์šฉ) : n - h
    -> H-Index : h์˜ ์ตœ๋Œ“๊ฐ’
- citations : ๋…ผ๋ฌธ์˜ ์ธ์šฉ ํšŸ์ˆ˜
- return H-Index

The source : https://ju-nam2.tistory.com/74

But this way takes longer than 1. Use Arrays.sort()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Arrays;

class Solution {
    public int solution(int[] citations) {
        int answer = 0;
        
        Arrays.sort(citations);
        int len = citations.length;
        int h = 0;
        int low = 0;
        int high = len - 1;
        
        while (low <= high) {
            int mid = (low + high) / 2;
            h = len - mid;
            
            if (citations[mid] >= h) {
                if (mid == 0) {
                    answer = h;
                    break;
                }
                
                if (mid != 0 && citations[mid - 1] <= h) {
                    answer = h;      // update
                    high = mid - 1;  // move to the left
                }
                else high = mid - 1;  // move to the left
            }
            else low = mid + 1; // move to the right
        } 
        
        return answer;
    }
}

The source : https://leetcode.com/problems/h-index-ii/discuss/1325353/java-binary-search-solution-ologn-time-o1-space


Actually, I came up with all of two ways. But, I couldnโ€™t apply thoseโ€ฆ. I have to learn more examples and get used to it.

I ate Chueotang in the morning, but it tasted not good compared to the other restaurant I often go hh. Iโ€™m gonna solve two more problems and go to bakery to buy sandwichs consisted of a half of basil chicken sandwich and a half of sweet pumpkin sandwich! It sounds like nnyami ๐Ÿ˜†

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Sort

[Algorithm] Hash

Comments powered by Disqus.