I was assigned a programming problem for homework, and I am at a stand-still. I have searched for hours today trying to find an answer, and it seems like it\'s never been asked
Think about how you'd do this with pen and paper.
The fact that the array is sorted allows you to optimize this algorthm by looking for the shortest consecutive run of equal numbers. That means you can do this in a single pass, with O(1)
auxiliary memory.
You can use an auxiliary array of length 201 since your range is [-100,100].
int[] counters = new int[201];
Suppose user entered -59, increment that specific counter: (You should add 100 to the entered number to find index, think of -100 is at index 0)
counters[-59 + 100]++;
Then iterate over the counters array and find the smallest non-zero element. Subtract 100 from that index, and that is the least frequent number surely.
int min = Integer.MIN_VALUE;
for(int i: counters)
{
if(i != 0 && i < min)
min = i;
}
Now, it means that counters[i]
has occured least frequent, which corresponds (i-100)
in actual value.
Two changes:
Initialize minCount
with biggest index i.e. 10 as:
private static int minCount = 10;
Change the if
to compare against less than
in place of greater than
as:
if(count < minCount){
This way you will change the minCount
with lower count, whenever you receive the lower occurence count and in the end, it will have the least.
I think, rest is fine. Hope this fixes your program.