We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The Full Counting Sort
The Full Counting Sort
+ 0 comments Failing last test due to timeout. Why ?
public class Solution { static class Result { /* * Complete the 'countingSort' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts INTEGER_ARRAY arr as parameter. */ public static void countSort(List<List<String>> arr) { // Write your code here int halfSize = arr.size()/2; List<List<String>> result = Stream.generate(ArrayList<String>::new).limit(100).collect(Collectors.toList()); for (int index=0;index<arr.size();index++){ // String number = arr.get(index).get(0); String value = arr.get(index).get(1); int pos = Integer.parseInt(arr.get(index).get(0)); if (index<halfSize) { result.get(pos).add("-"); } else { result.get(pos).add(value); } } // result.forEach(s -> System.out.println(s)); System.out.println(result.stream().map(item -> String.join(" ", item)).collect(Collectors.joining(" ")).trim()); return ; } } public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); List<List<String>> arr = new ArrayList<>(); int n = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0,n).forEach(i -> { try { arr.add(Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .collect(toList()) ); } catch (IOException e) { // TODO: handle exception throw new RuntimeException(); } }); Result.countSort(arr);
bufferedReader.close(); }
}
+ 0 comments def countSort(arr): # Write your code here for i in range(len(arr)//2): arr[i][1] = '-' ans = [] res = [0] * len(arr) for i in arr: res[int(i[0])] += 1 for i in range(len(res)): ans += [i] * res[i] ans = [[] for _ in range(ans[-1] + 1)] for i in arr: ans[int(i[0])].append(i[1]) print(' '.join(i for sublist in ans for i in sublist))
+ 0 comments This is my Java solutions in different Java versions, feel free to ask me any questions.
Updated Solution (Java 8):
public static void countSort(List<List<String>> arr) { // Initialize a set to store found indexes Set<Integer> indexes = new HashSet<>(); // Define constants final String sign = "-"; final int x = 100; //Maximum index final int n = arr.size(); // Initialize a counting list to store list strings List<StringBuilder> counts = new ArrayList<>(); // Create a String Builder for each index for(int i = 0; i <= x; i++) { counts.add(new StringBuilder()); } // Store strings that has the same index for(int i = 0; i < n; i++) { // Get index and source string from arr String indexString = arr.get(i).get(0); String source = arr.get(i).get(1); int index = Integer.parseInt(indexString); // Determine whether to use "-" for the source if(i < n/2) source = sign; // Append the source to corresponding StringBuilder // in the counts counts.get(index).append(source + " "); // Add the index to the set of found indexes indexes.add(index); } // Print the sorted string for(int index : indexes) { System.out.print(counts.get(index).toString()); } }
- Java 15 (The new version is faster and cleaner than the old ones)
public static void countSort(List<List<String>> arr) { int halfSize = arr.size()/2; List<List<String>> result = Stream .generate(ArrayList<String>::new) .limit(halfSize) .collect(Collectors.toList()); for(int i = 0; i < arr.size(); i++) { int index = Integer.valueOf(arr.get(i).get(0)); String value = arr.get(i).get(1); if(i < halfSize) { result.get(index).add("-"); } else { result.get(index).add(value); } } //Print the result System.out.println( result.stream() .map(item -> String.join(" ", item)) .collect(Collectors.joining(" ")) .trim() ); }
- Java 8 (Directly implement the count sort method in the main method instead of using references to avoid converting time)
public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); //Initialize the result list int halfSize = n/2; List<List<String>> result = Stream .generate(ArrayList<String>::new) .limit(halfSize) .collect(Collectors.toList()); for(int i = 0; i < n; i++) { int index = scanner.nextInt(); String value = scanner.next(); if(i < halfSize) { result.get(index).add("-"); } else { result.get(index).add(value); } }//end loop //Perform printing the result System.out.println( result.stream() .map(item -> String.join(" ", item)) .collect(Collectors.joining(" ")) .trim() ); scanner.close();; }
+ 0 comments JavaScript solution
/* * Complete the 'countSort' function below. * * The function accepts 2D_STRING_ARRAY arr as parameter. */ function countSort(arr) { // Write your code here let max = 0 for (let val of arr) { let integer = parseInt(val[0]) if (integer > max) max = integer } let fre = [] for (let i = 0; i < max + 1; i++) fre.push([]) for (let i = 0 ; i < arr.length ; i++) { let idx = parseInt(arr[i][0]) if (i < arr.length / 2) { fre[idx].push("-") } else { fre[idx].push(arr[i][1]) } } let res = "" for (let val of fre) res += val.join(" ") + " " console.log(res.trim()) }
+ 0 comments Well I was lucky, it worked once in some server later it didn't work again, so it depends on the cluster node where your code is running =0) . You can drop the OutputStream, maybe should be flushed before running it since others are running things there.
Here is my code:
class Result { static class Bucket { List<List<String>> pairs; public Bucket(){ this.pairs = new ArrayList<List<String>>(); } } public static void countSort(List<List<String>> arr) throws Exception{ final int MAX_N = 101; Bucket[] sorted = new Bucket[MAX_N]; int i = 0; while(i<MAX_N) { sorted[i]=new Bucket(); i++;} int half = arr.size()/2; for(int j=0; j<arr.size();j++){ List<String> pair = arr.get(j); int k = Integer.parseInt(pair.get(0)); if(j<half){ pair.add(1, "-");} sorted[k].pairs.add(pair); } OutputStream out = new BufferedOutputStream ( System.out ); i = 0; StringBuffer tmps = new StringBuffer(""); int j = 0; while(i<MAX_N) { for(List<String> pair: sorted[i].pairs){ tmps.append(pair.get(1)).append(' '); j++; } if(j%1000==0){ System.out.print(tmps.toString()); tmps = new StringBuffer(""); } i++; } if(tmps.length()>0) System.out.print(tmps.toString()); out.flush(); } }
Load more conversations
Sort 689 Discussions, By:
Please Login in order to post a comment