Skip to content

Instantly share code, notes, and snippets.

@kolauren
Created January 29, 2013 23:33
Show Gist options
  • Select an option

  • Save kolauren/4669033 to your computer and use it in GitHub Desktop.

Select an option

Save kolauren/4669033 to your computer and use it in GitHub Desktop.
interview practice
import java.util.*;
public class Test {
// You are given an array with n positive integers where all values in the array are repeated except for one.
// Return the one that is not repeated.
// brute force answer
public static int notRepeated_bf(int[] integers) {
int not_repeated;
int current_num;
boolean duplicate = false;
for(int i = 0; i < integers.length; i++) {
duplicate = false;
current_num = integers[i];
System.out.println(current_num);
for(int j = 0; j < integers.length; j++) {
System.out.println("Comparing " + integers[j] + " to " + current_num);
if (integers[j] == current_num && j != i) {
//its a duplicate
duplicate = true;
}
}
if (duplicate == false) {
return current_num;
}
}
return -1;
}
// "optimal"
public static int notRepeated(int[] ints) {
Map<Integer, Integer> m = new HashMap<Integer,Integer>();
for(int i = 0; i < ints.length; i++) {
if(m.containsKey(ints[i])) {
m.put(ints[i], m.get(ints[i]) + 1);
} else {
m.put(ints[i], 1);
}
}
for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
int key = entry.getKey();
int occurences = entry.getValue();
if (occurences == 1) {
return key;
}
}
return -1;
}
public static void main(String[] args) {
int[] b = new int[5];
b[0] = 1;
b[1] = 1;
b[2] = 3;
b[3] = 4;
b[4] = 3;
int a = notRepeated(b);
System.out.println(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment