Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Vytvoríme skupiny čísel, ktoré budú obsahovať rovnaké čísla. Výsledok je veľkosť poľa bez veľkosti najväčšej skupiny.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.*; public class EqualizeTheArray { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = stdin.nextInt(); } Map<Integer, Integer> numCount = new HashMap<>(); for(int i = 0; i < n; i++) { int count = numCount.getOrDefault(array[i], 0); numCount.put(array[i], count + 1); } int maxCount = numCount.values().stream().max( (Integer o1, Integer o2) -> o1 - o2 ).orElse(0); System.out.println(n - maxCount); stdin.close(); } } |
JavaScript
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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const array = lines[1].split(' '); const numCounts = {}; for(let i = 0; i < array.length; i++) { let count = numCounts[array[i]] || 0; numCounts[array[i]] = count + 1; } let maxCount = 0; for(let p in numCounts) { if(numCounts.hasOwnProperty(p) && numCounts[p] > maxCount) { maxCount = numCounts[p]; } } console.log(array.length - maxCount); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 |
import scala.io.Source object EqualizeTheArray extends App { val lines = Source.stdin.getLines().toList val array = lines(1).split(" ").map(_.toInt) val maxOccuredNumber = array.groupBy(n => n).map(_._2.length).max val toRemove = array.length - maxOccuredNumber println(toRemove) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
n = gets.strip.to_i arr = gets.strip.split num_counts = Hash.new arr.each do |num| count = 0 count = num_counts[num] if num_counts.has_key?(num) num_counts[num] = count + 1 end max_count = 0 num_counts.each_key do |key| count = num_counts[key] max_count = count if count > max_count end puts n - max_count |