Skip to content

Instantly share code, notes, and snippets.

@AriTedeschi
Created April 14, 2024 13:13
Show Gist options
  • Save AriTedeschi/043d440b710a1a67263e590267ba5bf8 to your computer and use it in GitHub Desktop.
Save AriTedeschi/043d440b710a1a67263e590267ba5bf8 to your computer and use it in GitHub Desktop.
Single number problem Java
import java.util.HashMap;
import java.util.Collections;
import java.util.Map;
public class Main
{
public interface RepetitionChecker {
int SingleNumber(int[] sequence);
}
public static class OnlyRepeatTwice implements RepetitionChecker{
public int SingleNumber(int[] sequence){
int once = 0;
for(int idx=0; idx < sequence.length ; idx++)
once = (once ^ sequence[idx]);
return once;
}
}
public static class OnlyRepeatThreeTimes implements RepetitionChecker{
public int SingleNumber(int[] sequence){
int once = 0;
int twice = 0;
for(int idx=0; idx < sequence.length ; idx++){
once = canBeSettedInFlag(sequence[idx], once, twice);
twice = canBeSettedInFlag(sequence[idx], twice, once);
}
return once;
}
private int canBeSettedInFlag(int e, int destinationFlag, int anotherFlag){
destinationFlag = (destinationFlag ^ e) & ~ anotherFlag;
return destinationFlag;
}
}
public static class RepetitionFactory {
private final Map<Integer, RepetitionChecker> checkers;
RepetitionFactory() {
Map<Integer, RepetitionChecker> tempMap = new HashMap<>();
tempMap.put(2, new OnlyRepeatTwice());
tempMap.put(3, new OnlyRepeatThreeTimes());
this.checkers = Collections.unmodifiableMap(tempMap);
}
public RepetitionChecker getInstance(int repeats){
return checkers.get(repeats);
}
}
public static void main(String[] args) {
int[] sequence = {1,2,4,2,1};
System.out.println("re=" + new RepetitionFactory().getInstance(2).SingleNumber(sequence));
int[] sequence2 = {10,20,20,30,20,10,10};
System.out.println("re=" + new RepetitionFactory().getInstance(3).SingleNumber(sequence2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment