bhumik3
BAN USERenum Result {
BULL, COW;
}
public static void guess(String str1, String str2) {
Result[] result = new Result[str1.length()];
for (int i = 0; i < str2.length(); i++) {
int index = str1.indexOf(str2.charAt(i));
if (index == -1) {
continue;
} else {
if (i < str1.length() && str1.charAt(i) == str2.charAt(i)) {
result[index] = Result.BULL;
} else if (result[index] == null) {
if (index == i) {
result[index] = Result.BULL;
} else {
result[index] = Result.COW;
}
}
}
}
int bulls = 0;
int cows = 0;
for (int i = 0; i < result.length; i++) {
if (result[i] == Result.BULL) {
bulls++;
} else if (result[i] == Result.COW) {
cows++;
}
}
System.out.println("Bulls: " + bulls + " Cows: " + cows);
}
I think the question is already properly answered, but I had one thought about using extra space and avoid visiting some elements. In other words, all the elements surrounding the mountain element are not going to be the mountain element, hence there is no need to check all eight surrounding elements for them.
Any thoughts about the extra efficiency introduced by using extra space?
Moore's voting algorithm is most optimal way to solve this. Thanks to the ones who suggested this. Here is my java implementation.
public static int findMaximumFrequency(int[] array) {
int len = array.length;
int currentIndex = 0;
int count = 1;
for (int i = 2; i < len; i++) {
if (array[i] == array[currentIndex]) {
count++;
} else {
count--;
}
if (count == 0) {
currentIndex = i;
count = 1;
}
}
int tempCounter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == array[currentIndex]) {
tempCounter++;
}
}
if (tempCounter > len / 2) {
return array[currentIndex];
} else {
return -1;
}
}
I feel that the problem is already answered but I have one question regarding calculating the distance. Since we are eventually comparing the relative distance, will it be okay and efficient to use distance which is: |x2 - x1| + |y2 - y1|.
This may be a pre-mature optimization, but what do you think?
Loved this code.
- bhumik3 November 24, 2014