Created
May 28, 2019 02:09
-
-
Save cdmunoz/ec91bd21cf467b9b28b68d9a2bc0b19a to your computer and use it in GitHub Desktop.
Kotlin's solution for Hackerrank's Lonely Integer excercise
https://www.hackerrank.com/challenges/lonely-integer/problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hakerrank | |
import java.io.* | |
import java.math.* | |
import java.security.* | |
import java.text.* | |
import java.util.* | |
import java.util.concurrent.* | |
import java.util.function.* | |
import java.util.regex.* | |
import java.util.stream.* | |
import kotlin.collections.* | |
import kotlin.comparisons.* | |
import kotlin.io.* | |
import kotlin.jvm.* | |
import kotlin.jvm.functions.* | |
import kotlin.jvm.internal.* | |
import kotlin.ranges.* | |
import kotlin.sequences.* | |
import kotlin.text.* | |
/** | |
* | |
* https://www.hackerrank.com/challenges/lonely-integer/problem | |
* | |
* You will be given an array of integers. All of the integers except one occur twice. That one is unique in the array. | |
* Given an array of integers, find and print the unique element. For example, a = [1,2,3,4,3,2,1], the unique element is 4. | |
* Function Description: | |
* Complete the lonelyinteger function in the editor below. It should return the integer which occurs only once in the input array. | |
* lonelyinteger has the following parameter(s): | |
* a: an array of integers | |
* Input Format | |
* The first line contains a single integer, n, denoting the number of integers in the array. | |
* The second line contains n space-separated integers describing the values in a. | |
* Constraints | |
* 1<=n<100 | |
* It is guaranteed that n is an odd number and that there is one unique element. | |
* 0<=a[i]<=100, where 0<=i<n. | |
* Output Format | |
* Print the unique integer in the array. | |
*/ | |
// Complete the lonelyinteger function below. | |
fun lonelyinteger(a: Array<Int>): Int { | |
val map = mutableMapOf<Int, Int>() | |
a.forEach { | |
if (!map.containsKey(it)) { | |
map[it] = it | |
}else{ | |
map.remove(it) | |
} | |
} | |
var lonely = 0 | |
for (entry in map) lonely = entry.value | |
return lonely | |
} | |
fun main(args: Array<String>) { | |
val scan = Scanner(System.`in`) | |
val n = scan.nextLine().trim().toInt() | |
val a = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray() | |
val result = lonelyinteger(a) | |
println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment