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
2. Use Binary Search
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 ๐
Comments powered by Disqus.