Java - Finding the least common integer in a sorted array

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

提交回复
热议问题