在C ++中计算连续元素相差1的子数组
给我们一个包含整数的数组arr[]。目的是对arr[]的所有子数组进行计数,以使每个子数组中的连续元素仅相差1。如果数组是[1,2,3]。子数组将仅是[1,2],[2,3],[1,2,3]。
让我们通过示例来理解。
输入−arr[]={4,3,2,1};
输出-连续元素相差1的子数组的计数为-6
说明-Subaarays将是-
[4,3], [3,2], [2,1], [4,3,2], [3,2,1], [4,3,2,1]. Total 6.
输入−arr[]={1,5,6,7,9,11};
输出-连续元素相差1的子数组的计数为-3
说明-Subaarays将是-
[5,6], [6,7], [5,6,7]. Total 3
以下程序中使用的方法如下
我们将使用for循环遍历数组。从i=0到i<大小。然后检查是否有任何元素与其相邻元素相差1。如果是,则将索引存储为第一个。如果不是,则将子数组中的元素数作为临时数(first-last+1)。索引首尾之间的数组的所有连续元素相差1。因此,子数组总数为temp*(temp-1)/2。添加此计数。为具有所有连续元素的下一个数组更新索引first=last=i。
取数字的数组arr[]。
函数sub_ele_diff_one(intarr[],intsize)获取数组,并返回连续元素相差1的子数组计数。
将初始计数设为0。
我们将使用从i=0到I<size的for循环遍历数组。
首先取两个变量,最后取0作为所有元素连续且相差1的索引。
检查arr[i-1]-arr[i]==1或arr[i]-arr[i-1]==1。(元素相差1)。如果为true,请先增加。
如果先前条件为假,则满足此条件的数组中的元素总数为temp=first-last+1。可能的子数组为total=temp*(temp-1)/2。
现在添加此子数组的总数为count。
首先以当前I(连续元素条件失败的索引)更新索引。
在for循环的末尾,如果first!=last。这意味着其余数组满足条件。应用相同的步骤,然后将总数加到计数中。
在两个循环的最后,返回count作为结果。
示例
#include <iostream> using namespace std; int sub_ele_diff_one(int arr[], int size){ int count = 0, first = 0, last = 0; for (int i = 1; i < size; i++){ if (arr[i] - arr[i - 1] == 1 || arr[i-1] - arr[i] == 1){ first++; } else{ int temp = first - last + 1; int total = temp * (temp - 1) / 2; count = count + total; first = i; last = i; } } if (first != last){ int temp = first - last + 1; int total = temp * (temp - 1) / 2; count = count + total; } return count; } int main(){ int arr[] = { 1, 2, 4, 3 }; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of Subarrays with Consecutive elements differing by 1 are: "<<sub_ele_diff_one(arr, size); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of Subarrays with Consecutive elements differing by 1 are: 2