Find the stray number in Java

The challenge

You are given an odd-length array of integers, in which all of them are the same, except for one single number.

Complete the method which accepts such an array, and returns that single different number.

The input array will always be valid! (odd-length >= 3)

Examples

[1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3
Code language: PHP (php)

The solution in Java code

Option 1:

import java.util.*; class Solution { static int stray(int[] numbers) { Map<Integer, Integer> map = new HashMap<>(); for (int i=0; i<numbers.length; i++) { Integer def = map.getOrDefault(numbers[i], 0); map.put(numbers[i], ++def); } for(Integer key : map.keySet()) { System.out.println(key); System.out.println(map.get(key)); if (map.get(key)==1) return key; } return 0; } }
Code language: Java (java)

Option 2:

class Solution { static int stray(int[] numbers) { if (numbers[0] != numbers[1] && numbers[0] != numbers[2]) return numbers[0]; for (int i : numbers) if (i != numbers[0]) return i; return 0; } }
Code language: Java (java)

Option 3:

import java.util.Arrays; class Solution { static int stray(int[] numbers) { return Arrays.stream(numbers).reduce(0, (a, b) -> a ^ b); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void simpleArray1() { assertEquals(2, getActualFor(1, 1, 2)); } @Test public void simpleArray2() { assertEquals(3, getActualFor(17, 17, 3, 17, 17, 17, 17)); } @Test public void firstItem() { assertEquals(8, getActualFor(8, 1, 1, 1, 1, 1, 1)); } @Test public void lastItem() { assertEquals(0, getActualFor(1, 1, 1, 1, 1, 1, 0)); } @Test public void middleItem() { assertEquals(7, getActualFor(0, 0, 0, 7, 0, 0, 0)); } @Test public void fifthItem() { assertEquals(-6, getActualFor(-21, -21, -21, -21, -6, -21, -21)); } @Test public void randomSmallArray() { int strayNumber = SolutionHelper.randomInt(-10000, 10000); int[] array = SolutionHelper.validRandomArray(101, strayNumber); assertEquals(strayNumber, getActualFor(array)); } @Test public void randomBigArray() { int strayNumber = SolutionHelper.randomInt(-10000, 10000); int[] array = SolutionHelper.validRandomArray(15273, strayNumber); assertEquals(strayNumber, getActualFor(array)); } private int getActualFor(int... numbers) { return Solution.stray(numbers); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments