Lonely Integer - Given an array of integers, where all elements but one occur twice, find the unique element. Hackerrank Solution
Given an array of
integers, where all elements but one occur twice, find the unique element.
Example
a = [1, 2, 3, 4, 3,
2 ,2]
The unique element
is 4.
Function
Description
Complete the lonelyinteger function
in the editor below.
lonelyinteger has
the following parameter(s):
· int a[n]: an array of integers
Returns
· int: the element that occurs only once
Input Format
The first line
contains a single integer,n , the number of integers in the array.
The second line contains n space-separated integers that describe
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.
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 static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
// solution
class Result {
public static int lonelyinteger(List a) {
int count = 0;
ArrayList al = new ArrayList<>();
for (Integer i : a) {
count = 0;
for (Integer j : a) {
if (i==j) {
count += 1;
}
}
if(count == 1){
al.add(i);
}
}
return al.get(0);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
int result = Result.lonelyinteger(a);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
In Python
import math
import os
import random
import re
import sys
def lonelyinteger(a):
for i in a:
count = 0
for j in a:
if i == j:
count += 1
if count == 1:
return i
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
result = lonelyinteger(a)
fptr.write(str(result) + '\n')
fptr.close()
Comments
Post a Comment