簡體   English   中英

如何找到 c++ 中的第一個最大值?

[英]How to find the first maximum in c++?

我搜索最長范圍的數組。 數組元素為:2 3 4 7 8,結果為 2-4。 如果數組有 2 個或更多相同的范圍怎么辦。 怎樣才能找到第一個?

for (int i = 0; i < n-1; i++) {
        if (t[i] == t[i+1] -1) {
            cur++;
        }
        else {
            if (cur> max) {
                max = cur;
                first= cur_first;
                last= t[i];
            }
            cur= 1;
            cur_first= t[i+1];
        }

    }
    if (cur> max) {
        cur= max;
        first= cur_first;
        last= t[n-1];
    }

如果您在內部添加另一個循環只是為了獲取范圍,它會更簡單(更快)。

int t[] = {2,3,4,7,8,2,3,4};
int n = sizeof(t)/sizeof(t[0]);

struct {
    int idx;  //start index.
    int len;  //length of range.
} cur, max = {0,1};

for (int i = 0; i < n-1; i++) {
    //---get the current range.
    cur.len = 1;
    cur.idx = i;
    while(t[i]==t[i+1]-1){
        cur.len++; i++;
        if(i >= n-1) break;
    }
    //---save the range with maximum length.
    if(cur.len > max.len){
        max = cur;

        if(max.len > n-i-1) break;  //optimization code. can be optional.

    }
}

printf("max range: idx=%d; len=%d; firstValue=%d",max.idx, max.len, t[max.idx]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM