How do I find the mode of a sorted array?

前端 未结 4 862
囚心锁ツ
囚心锁ツ 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条回答
  •  萌比男神i
    2021-01-20 16:13

    If the input array is sorted, here is the same approach as described in other answers but implemented in a different way, a better and easy to understand way.

    1. Run a loop over the input array.
    2. Keep global mode value and mode count.
    3. Run a sliding window till you find equal elements.
    4. If local equal element count is greater than global mode count, then update global mode and mode count.

    Here is working and tested code in C++.

    int mode(vector a, int N)
    {
        int mode = a[0];
        int mode_count = 1;
        int i = 0;
        while (i < N - 1) {
            int cur = a[i];
            int cur_count = 1;
            while (a[i] == a[i + 1]) {
                i++;
                cur_count++;
            }
            if (cur_count > mode_count) {
                mode_count = cur_count;
                mode = a[i];
            }
            i++;
        }
        return mode;
    }
    

提交回复
热议问题