C语言中数组中相同元素之间最大距离
给定一个整数数组。数组中包含多个相同元素。这里的任务是找到数组中任意两个相同元素之间的最大距离。我们将从左到右拾取数组中的每个元素。然后我们将找到相同数字的最后一次出现并存储索引之间的差值。现在,如果此差值最大,则返回它。
输入
Arr[] = { 1,2,4,1,3,4,2,5,6,5 }
输出 - 数组中相同元素之间最大距离 - 4
解释 - 重复数字及其索引 -
1. 1, first index 0, last index 3 distance=3-0-1=2 2. 2, first index 1, last index 6 distance=6-1-1=4 3. 5, first index 7, last index 9 distance=9-7-1=1 Maximum distance between two occurrences of same element : 4
输入
Arr[] = { 10,20,1,10,10,21,12,0 }
输出 - 数组中相同元素之间最大距离 - 3
解释 - 重复数字及其索引 -
1. 10 first index 0, last index 4 distance=4-0-1=3 Maximum distance between two occurrences of same element : 3
注意 - 如果输入数组没有重复数字,则返回 -1
下面程序中使用的方案如下
我们取一个包含重复数字的整数数组 Arr[]
函数 maxDistance( int arr[],int n) 用于计算相同元素之间最大距离。
我们将变量 maxD 初始化为 -1。
在 for 循环内部从开头遍历整数数组。
在嵌套 for 循环中遍历其余元素并搜索是否存在重复项。(if ( arr[i] == arr[j] )。
如果为真,则通过减去索引来计算数字之间的差值。(temp=j-i-1)
如果此值为迄今为止找到的最大值,则将其存储在 maxD 中
遍历整个数组后返回 maxD。
示例
#include <stdio.h> #include <math.h> int maxDistance(int arr[],int n){ int size = n; int maxD = -1; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]){ int temp=abs(j-i-1); maxD = maxD>temp?maxD:temp; } return maxD; } // Driver code int main(){ int Arr[] = {1,2,4,1,3,4,2,5,6,5}; printf("Maximum distance between two occurrences of same element in array:%d", maxDistance(Arr,10) ); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行以上代码,它将生成以下输出 -
Maximum distance between two occurrences of same element in array − 4
广告