How do I find the mode of a sorted array?

前端 未结 4 858
囚心锁ツ
囚心锁ツ 2021-01-20 15:41

I need to write a function to find the mode of a array. I\'m not good at coming up with algorithms however and I\'m hoping someone else knows how to do this.

I know

4条回答
  •  轮回少年
    2021-01-20 16:09

    You have almost everything.

    You can take advantage of the fact that the array is sorted.

    Just go through the array keeping track of both the current equal consecutive numbers, and the greatest number of equal consecutive numbers you have found until that point (and which number produced it). In the end you will have the greatest number of equal consecutive numbers and which number produced it. That will be the mode.

    Note: For a solution which does not require the array to be sorted, see for example one based in the histogram approach in a related question.

提交回复
热议问题