Skip to content

Find the unique number using Java

The challenge

There is an array with some numbers. All numbers are equal except for one. Try to find it!

Solution.findUniq(new double[]{ 1, 1, 1, 2, 1, 1 }); // => 2 Solution.findUniq(new double[]{ , , 0.55, , }); // => 0.55
Code language: Java (java)

It’s guaranteed that array contains at least 3 numbers.

The tests contain some very huge arrays, so think about performance.

The solution in Java code

Option 1:

import java.util.Arrays; public class Solution { public static double findUniq(double[] arr) { Arrays.sort(arr); return arr[] == arr[1] ? arr[arr.length-1]:arr[]; } }
Code language: Java (java)

Option 2:

public class Solution { public static double findUniq(double arr[]) { final double x = arr[arr[] == arr[1] ? : 2]; for (double y : arr) if (y != x) return y; throw new RuntimeException("no unique number found"); } }
Code language: Java (java)

Option 3:

import java.util.Arrays; import java.util.Map.Entry; import static java.util.function.Function.identity; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; class Solution { static double findUniq(final double[] array) { return Arrays.stream(array).boxed() .collect(groupingBy(identity(), counting())) .entrySet().stream() .filter(e -> e.getValue() == 1) .findFirst() .map(Entry::getKey) .orElse(0.0); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class FindUniqTest { private double precision = 0.0000000000001; @Test public void sampleTestCases() { assertEquals(1.0, Solution.findUniq(new double[]{, 1, }), precision); assertEquals(2.0, Solution.findUniq(new double[]{1, 1, 1, 2, 1, 1}), precision); } }
Code language: Java (java)

See also  How to Swap Node Pairs In Linked List in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x