How do I find the mode of a sorted array?

前端 未结 4 872
囚心锁ツ
囚心锁ツ 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:26

    set most_found_element to the first element in the array
    set most_found_element_count to zero
    set current_element to the first element of the array
    set current_element_count to zero
    for each element e in the array
        if e is the same as the current_element
            increase current_element_count by one
        else
            if current_element_count is greater than most_found_element_count
                set most_found_element to the current_element
                set most_found_element_count to current_element_count
            set current_element to e
            set current_element_count to one
    if current_element_count is greater than most_found_element_count
        set most_found_element to the current_element
        set most_found_element_count to current_element_count
    print most_found_element and most_found_element_count
    

    I thought the names would explain it, but here we go:

    When we start, no element has been found the most times
      so the "high-score" count is zero.
    Also, the "current" value is the first, but we haven't looked at it yet 
      so we've seen it zero times so far
    Then we go through each element one by one
      if it's the same as "current" value, 
         then add this to the number of times we've seen the current value.
      if we've reached the next value, we've counted all of the "current" value.
         if there was more of the current value than the "high-score"
            then the "high-score" is now the current value
         and since we reached a new value
            the new current value is the value we just reached
    Now that we've seen all of the elements, we have to check the last one
      if there was more of the current value than the "high-score"
        then the "high-score" is now the current value
    Now the "high-score" holds the one that was in the array the most times!
    

    Also note: my original algorithm/code had a bug, we have to do an extra check of "current" after the loop ends, as it never finds "the one after the last".

提交回复
热议问题