Java - Finding the least common integer in a sorted array

后端 未结 3 1296
梦毁少年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: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.

提交回复
热议问题