查找起始索引&阵列中运行时间最长的长度? C ++

时间:2018-03-19 05:59:06

标签: c++ algorithm

对于给定的数组

int arr[0] = {0,1,0,0,0};

我需要返回最长时间0

的起始索引

所以在这种情况下

findIndex(arr)

将返回另一个数组result = {2,3}。 2表示运行的起始索引,3表示运行的长度。

这是我的尝试,只能找到长度而不是索引

int findLongestConseqSubseq(int arr[], int n)
{
int max = 1;
int current = 1;
int i;

for (i = 1; i < n; i++) {
    if (arr[i - 1] == arr[i])
    {    /* the run continues */
        current++;
        max = current > max ? current : max;
    }
    else
    {    /* the run was broken */
        current = 1;
    }
}
return max; 
}

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

除了仅保存[Required] [DataType(DataType.Password)] public string Password { get; set; } [Required] [DataType(DataType.Password)]`enter code here` [Compare("Password")] public string ConfirmPassword { get; set; } 之外,还要保存索引。而不是从max返回0的最长篇幅,您可以返回findLongestConseqSubseq()第一个元素表示索引,第二个元素表示最大长度。

pair<int,int>

答案 1 :(得分:0)

您可以使用两个变量curr_index&amp; max_index存储当前运行和最长运行的索引,并在更新最大值时更新它们。

此外,每次找到匹配项时都不需要更新最大值,只需在运行完成时更新它。

int curr_index = 0, max_index = 0;
if (arr[i - 1] == arr[i]) {    
    /* the run continues */
    current++;
}
else {    
    /* the run was broken */
    if(current > max) {
        max = current;
        max_index = index;
        curr_index = i;
    } 
    current = 1;
}
相关问题