Find largest Max list in an array

时间:2015-10-06 08:39:23

标签: c++

I need to find the first Max list of an array and find it's middle. In other words, having for example this array {2, 8, 8, 8, 8, 8, 6, 3, 8, 8, 8} I need to have as a result the index 3, which is the middle of the first max list. I did try but my C++ code is still missing something. Can you please help. Thanks

The following code is just a sample what I'm working on is an 90 elements array.

#include <iostream>
using namespace std;
int main()
{ 
    int array[] = {2, 8, 8, 8, 8, 8, 6, 8, 0};
    int Max = 0;
    int StartMax = 0, EndMax = 0;

    for (int m = 0 ; m < 9 ; m++){

        if(array[m] > Max){
            Max = array[m];
            StartMax = m;
            EndMax = m;
            cout << "array[m] > Max " << Max << endl;
        }

        else if(array[m] < Max){
            cout << "array[m] < Max " << Max << endl;
        }

        else { 
            int a = array[m] - array[m-1];
            cout << "a = " << a << endl;

            if (a == 0){ 
                cout << "a = " << a << endl;
                EndMax = m;
            }
        }
    }
    cout << "Index of Max : " << ((StartMax+EndMax)/2) << endl; 
}

1 个答案:

答案 0 :(得分:1)

问题

您的代码适用于此示例,但是当您拥有第二个&#34; max list&#34;它有2个以上的元素。

确实与array[] = {2, 8, 8, 8, 8, 8, 6, 8, 8};(注意最后8个)
我们得到结果:middle=4而不是middle3,因为当您再次遇到8时输入此分支条件:

else { 
   int a = array[m] - array[m-1];

然后输入分支if (a==0)并将EndMax设置为数组的末尾!
StartMax = 1Endmax = 8因此middle = 4 这不是你想要的!

Live Code

解决方案

我建议使用布尔跟踪器来管理它:

size_t give_middle_max_list(const std::vector<int>& v) {
    size_t idx_start_max = 0;
    size_t idx_end_max = 0;
    int max_val = v[0];
    bool should_continue = false;

    for(size_t i = 1; i < v.size(); i ++) {
        if(v[i] > max_val) {
            max_val = v[i];
            idx_start_max = i;
            idx_end_max = i;
            should_continue = true;
        }
        else {
            if (v[i] == max_val && should_continue == true) {
                idx_end_max = i;   // I am still in the first max list 
            }
            else {
                should_continue = false; // I am not in the first max list anymore !
            }
        }
    }
    std::cout << idx_start_max << ";" << idx_end_max << std::endl;
    return (idx_end_max + idx_start_max) / 2;
}

<强> Live code