📌  相关文章
📜  计算连续元素相差 1 的子数组

📅  最后修改于: 2022-05-13 01:57:47.270000             🧑  作者: Mango

计算连续元素相差 1 的子数组

给定一个包含 N 个整数的数组 arr[]。任务是计算给定数组的子数组的总数,使得子数组中的连续元素之间的差为 1。也就是说,对于任何索引i  在子数组中, arr[i+1] – arr[i] = 1
注意:不要考虑具有单个元素的子数组。
例子:

Input : arr[] = {1, 2, 3}
Output : 3
The subarrays are {1, 2}. {2, 3} and {1, 2, 3}

Input : arr[] = {1, 2, 3, 5, 6, 7}
Output : 6

朴素方法:一种简单的方法是运行两个嵌套循环并检查每个子数组并计算连续元素相差 1 的子数组的计数。
有效方法:一种有效的方法是观察在长度为K的数组中,大小大于 1 的子数组的总数 = (K)*(K-1)/2。
因此,想法是通过使用两个指针来遍历数组,在最大长度的窗口中计算具有连续元素的子数组,然后使用上述公式计算该窗口中的所有子数组。
下面是逐步算法:

  • 取两个指针fastslow ,用于维护连续元素的窗口。
  • 开始遍历数组。
  • 如果元素相差 1,则仅增加快速指针。
  • 否则,计算索引fastslow之间的当前窗口长度。

以下是给定方法的实现:

C++
// C++ program to count Subarrays with
// Consecutive elements differing by 1
 
#include 
using namespace std;
 
// Function to count Subarrays with
// Consecutive elements differing by 1
int subarrayCount(int arr[], int n)
{
    // Variable to store count of subarrays
    // whose consecutive elements differ by 1
    int result = 0;
 
    // Take two pointers for maintaining a
    // window of consecutive elements
    int fast = 0, slow = 0;
 
    // Traverse the array
    for (int i = 1; i < n; i++) {
 
        // If elements differ by 1
        // increment only the fast pointer
        if (arr[i] - arr[i - 1] == 1) {
            fast++;
        }
        else {
 
            // Calculate length of subarray
            int len = fast - slow + 1;
 
            // Calculate total subarrays except
            // Subarrays with single element
            result += len * (len - 1) / 2;
 
            // Update fast and slow
            fast = i;
            slow = i;
        }
    }
 
    // For last iteration. That is if array is
    // traversed and fast > slow
    if (fast != slow) {
        int len = fast - slow + 1;
        result += len * (len - 1) / 2;
    }
 
    return result;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 3, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << subarrayCount(arr, n);
 
    return 0;
}


Java
// Java program to count Subarrays with
// Consecutive elements differing by 1
class cfg
{
 
// Function to count Subarrays with
// Consecutive elements differing by 1
static int subarrayCount(int arr[], int n)
{
    // Variable to store count of subarrays
    // whose consecutive elements differ by 1
    int result = 0;
 
    // Take two pointers for maintaining a
    // window of consecutive elements
    int fast = 0, slow = 0;
 
    // Traverse the array
    for (int i = 1; i < n; i++) {
 
        // If elements differ by 1
        // increment only the fast pointer
        if (arr[i] - arr[i - 1] == 1) {
            fast++;
        }
        else {
 
            // Calculate length of subarray
            int len = fast - slow + 1;
 
            // Calculate total subarrays except
            // Subarrays with single element
            result += len * (len - 1) / 2;
 
            // Update fast and slow
            fast = i;
            slow = i;
        }
    }
 
    // For last iteration. That is if array is
    // traversed and fast > slow
    if (fast != slow) {
        int len = fast - slow + 1;
        result += len * (len - 1) / 2;
    }
 
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
 
    int arr[] = { 1, 2, 3, 5, 6, 7 };
    int n = arr.length;
 
    System.out.println(subarrayCount(arr, n));
 
}
}
//This code is contributed by Mukul Singh


Python3
# Python3 program to count Subarrays with
# Consecutive elements differing by 1
 
# Function to count Subarrays with
# Consecutive elements differing by 1
def subarrayCount(arr, n) :
     
    # Variable to store count of subarrays
    # whose consecutive elements differ by 1
    result = 0
 
    # Take two pointers for maintaining a
    # window of consecutive elements
    fast, slow = 0, 0
 
    # Traverse the array
    for i in range(1, n) :
 
        # If elements differ by 1
        # increment only the fast pointer
        if (arr[i] - arr[i - 1] == 1) :
            fast += 1
         
        else :
 
            # Calculate length of subarray
            length = fast - slow + 1
 
            # Calculate total subarrays except
            # Subarrays with single element
            result += length * (length - 1) // 2;
 
            # Update fast and slow
            fast = i
            slow = i
 
    # For last iteration. That is if array is
    # traversed and fast > slow
    if (fast != slow) :
        length = fast - slow + 1
        result += length * (length - 1) // 2;
     
    return result
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 5, 6, 7 ]
    n = len(arr)
 
    print(subarrayCount(arr, n))
 
# This code is contributed by Ryuga


C#
// C# program to count Subarrays with
// Consecutive elements differing by 1
using System;
class cfg
{
 
// Function to count Subarrays with
// Consecutive elements differing by 1
static int subarrayCount(int []arr, int n)
{
    // Variable to store count of subarrays
    // whose consecutive elements differ by 1
    int result = 0;
 
    // Take two pointers for maintaining a
    // window of consecutive elements
    int fast = 0, slow = 0;
 
    // Traverse the array
    for (int i = 1; i < n; i++) {
 
        // If elements differ by 1
        // increment only the fast pointer
        if (arr[i] - arr[i - 1] == 1) {
            fast++;
        }
        else {
 
            // Calculate length of subarray
            int len = fast - slow + 1;
 
            // Calculate total subarrays except
            // Subarrays with single element
            result += len * (len - 1) / 2;
 
            // Update fast and slow
            fast = i;
            slow = i;
        }
    }
 
    // For last iteration. That is if array is
    // traversed and fast > slow
    if (fast != slow) {
        int len = fast - slow + 1;
        result += len * (len - 1) / 2;
    }
 
    return result;
}
 
// Driver Code
public static void Main()
{
 
    int []arr = { 1, 2, 3, 5, 6, 7 };
    int n = arr.Length;
 
    Console.WriteLine(subarrayCount(arr, n));
 
}
}
//This code is contributed by inder_verma..


PHP
 slow
    if ($fast != $slow)
    {
        $len = $fast - $slow + 1;
        $result += $len * ($len - 1) / 2;
    }
 
    return $result;
}
 
// Driver Code
$arr = array(1, 2, 3, 5, 6, 7);
$n = sizeof($arr);
 
echo subarrayCount($arr, $n);
 
// This code is contributed
// by Akanksha Rai
?>


Javascript


输出:
6

时间复杂度:O(N)
辅助空间:(1)