Source : https://www.hackerrank.com/challenges/countingsort3
In the previous challenge, it was easy to print all the integers in order, since you did not have to access the original list. Once you had obtained the frequencies of all the integers, you could simply print each integer in order the correct number of times. However, if there is other data associated with an element, you will have to access the original element itself.
In the final counting sort challenge, you are required to print the data associated with each integer. This means, you will go through the original array to get the data, and then use some "helper arrays" to determine where to place everything in a sorted array.
If you know the frequencies of each element, you know how many times to place it, but which index will you start placing it from? It will be helpful to create a helper array for the "starting values" of each element.
Challenge
You will be given a list that contains both integers and strings. In this challenge you just care about the integers. For every value from to , can you output , the number of elements that are less than or equal to ?
Input Format
- , the size of the list .
- lines follow, each containing an integer and a string .
Output Format
Output for all numbers from to (inclusive).
Constraints
length of string
Sample Input
10
4 that
3 be
0 to
1 be
5 question
1 or
2 not
4 is
2 to
4 the
Sample Output
1 3 5 6 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
Explanation
0 appears 1 time, so the 0th number is .
0 and 1 combined appear 3 times, so the next number is .
This continues for the rest of the list, until no more new numbers appear.
Source : https://www.hackerrank.com/challenges/countingsort3
Solution
// Karthikalapati.blogspot.com | |
import java.util.Scanner; | |
public class Solution { | |
public static void main(String[] args) { | |
final int maxValue = 100; | |
Scanner scan = new Scanner(System.in); | |
int n = scan.nextInt(); | |
int[] array = new int[maxValue]; | |
/* Save into buckets */ | |
for (int i = 0; i < n; i++) { | |
int num = scan.nextInt(); | |
scan.next(); // don't need the String | |
array[num]++; | |
} | |
scan.close(); | |
/* Print "L" for each bucket */ | |
int count = 0; | |
for (int i = 0; i < array.length; i++) { | |
count += array[i]; | |
System.out.print(count + " "); | |
} | |
} | |
} |
No comments:
Post a Comment