Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Find counts of all elements with the same value and print only these that their count is equals to 1.
I created solution in:
All solutions are also available on my GitHub.
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 25 26 27 |
import java.util.*; public class LonelyInteger { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); Map<Integer, Integer> array = new HashMap<>(); for(int i = 0; i < n; i++) { int num = stdin.nextInt(); Integer count = array.get(num); if(count == null) { array.put(num, 1); } else { array.put(num, count + 1); } } for(Integer key : array.keySet()) { if(array.get(key) == 1) { System.out.println(key); break; } } 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 |
function processData(input) { var arr = input.split("\n")[1].split(" ").map(function(item) {return parseInt(item)}); var hash = {}; for(var i = 0; i < arr.length; i++) { if(hash[arr[i]]) { hash[arr[i]] += 1; } else { hash[arr[i]] = 1; } } for(prop in hash) { if(hash.hasOwnProperty(prop) && hash[prop] == 1) { console.log(prop); return; } } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) {_input += input;}); process.stdin.on("end", function () {processData(_input);}); |
Scala
1 2 3 4 5 6 7 8 |
import scala.io.Source object LonelyInteger extends App { val arr = (Source.stdin.getLines().toList)(1).split(" ").map(_.toInt) val groups = arr.groupBy(i => i) val uniqueElement = groups.keys.find(key => groups.get(key).get.size == 1) println(uniqueElement) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 |
length = gets.chomp.to_i array = gets.chomp.split.map { |e| e.to_i } hash = Hash.new array.each do |i| if hash[i].nil? hash[i] = 1 else hash[i] += 1 end end array.each { |a| puts a if hash[a] == 1} |