对于给定的数组
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;
}
有什么想法吗?
答案 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;
}