Java - Finding the least common integer in a sorted array

后端 未结 3 1294
梦毁少年i
梦毁少年i 2021-01-21 04:34

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

相关标签:
3条回答
  • 2021-01-21 05:00

    Think about how you'd do this with pen and paper.

    1. Count the number of times each number appears in the array.
    2. Find the smallest count.
    3. Return the value corresponding to that count. This demands that you somehow stored the value mapped to its count.

    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.

    0 讨论(0)
  • 2021-01-21 05:02

    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.

    0 讨论(0)
  • 2021-01-21 05:20

    Two changes:

    1. Initialize minCount with biggest index i.e. 10 as:

      private static int minCount = 10;
      
    2. 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.

    0 讨论(0)
提交回复
热议问题