C language - return the length of the most consecutive identical numbers in the array

Title description:

Returns the length of the most consecutive identical numbers in the array,

Such as 1, 2, 2, 3, return 2   
such as 1, 2, 4, 4, 4, return 3 

//返回数组中连续相同数最宽的长度,如1,2,2,3,返回2   
// 如1,2,4,4,4,返回3
int SearchMaxwidth(int array[], int n) {
	int max = 0, i = 0, num;//定义 max 记录宽度,i 作为遍历索引,num 记录连续相同数值的数量
	int k = array[0];//k用来表示不同元素
	int k = 1;//k 用来表示所计数的是目前第k个不同元素
	while (i < n) {//遍历记录结点层数的数组 
		num = 0;//每次计数时都需初始化变量 num
		while (i < n && array[i] == k) {//对第k个不同元素结点进行计数 
			num++;
			i++;
		}
		k = array[i];
		if (num > max)//判断此层结点数是否为当前遍历过的最大宽度
			max = num;
	}
	return max;//返回此树的宽度 
}
int main() {
	int a[9] = { 1,2,3,4,4,5,5,6,7 };
	int n = 9;
	printf("%d", SearchMaxwidth(a, n));
	return 1;
}

This idea is involved in finding the maximum width of a binary tree.

Guess you like

Origin blog.csdn.net/knighthood2001/article/details/132152109