📌  相关文章
📜  元素 A[i] 的数量,使得 A[i] + 1 也存在于数组中

📅  最后修改于: 2021-09-06 11:27:11             🧑  作者: Mango

给定一个整数数组arr ,任务是计算元素 ‘A[i]’ 的数量,使得数组中也存在 A[i] + 1。
注意:如果数组中有重复项,则分别计数。
例子:

方法一:暴力破解
对于数组中的所有元素,检查所有元素后返回总计数

  • 对于当前元素x,计算x+1,并搜索x+1当前值前后的所有位置。
  • 如果找到 x + 1,则将总数加 1

下面是上述方法的实现:

C++
// C++ program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
#include 
using namespace std;
 
// Function to find the countElements
int countElements(int* arr, int n)
{
    // Initialize count as zero
    int count = 0;
 
    // Iterate over each element
    for (int i = 0; i < n; i++) {
 
        // Store element in int x
        int x = arr[i];
 
        // Calculate x + 1
        int xPlusOne = x + 1;
 
        // Initialize found as false
        bool found = false;
 
        // Run loop to search for x + 1
        // after the current element
        for (int j = i + 1; j < n; j++) {
            if (arr[j] == xPlusOne) {
                found = true;
                break;
            }
        }
 
        // Run loop to search for x + 1
        // before the current element
        for (int k = i - 1;
             !found && k >= 0; k--) {
            if (arr[k] == xPlusOne) {
                found = true;
                break;
            }
        }
 
        // if found is true, increment count
        if (found == true) {
            count++;
        }
    }
 
    return count;
}
 
// Driver program
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // call countElements function on array
    cout << countElements(arr, n);
 
    return 0;
}


Java
// Java program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
import java.io.*;
import java.util.Arrays;
 
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr, int n)
{
     
    // Initialize count as zero
    int count = 0;
     
    // Iterate over each element
    for (int i = 0; i < n; i++)
    {
     
        // Store element in int x
        int x = arr[i];
     
        // Calculate x + 1
        int xPlusOne = x + 1;
     
        // Initialize found as false
        boolean found = false;
     
        // Run loop to search for x + 1
        // after the current element
        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] == xPlusOne)
            {
                found = true;
                break;
            }
        }
     
        // Run loop to search for x + 1
        // before the current element
        for (int k = i - 1; !found && k >= 0; k--)
        {
            if (arr[k] == xPlusOne)
            {
                found = true;
                break;
            }
        }
     
        // If found is true, increment count
        if (found == true)
        {
            count++;
        }
    }
        return count;
}
     
// Driver code
public static void main (String[] args)
{
    int arr[] = { 1, 2, 3 };
    int n = arr.length;
     
    // Call countElements function on array
    System.out.println(countElements(arr, n));
}
}
 
//This code is contributed by shubhamsingh10


Python3
# Python3 program to count of elements
# A[i] such that A[i] + 1
# is also present in the Array
 
# Function to find the countElements
def countElements(arr,n):
    # Initialize count as zero
    count = 0
 
    # Iterate over each element
    for i in range(n):
 
        # Store element in int x
        x = arr[i]
 
        # Calculate x + 1
        xPlusOne = x + 1
 
        # Initialize found as false
        found = False
 
        # Run loop to search for x + 1
        # after the current element
        for j in range(i + 1,n,1):
            if (arr[j] == xPlusOne):
                found = True
                break
 
        # Run loop to search for x + 1
        # before the current element
        k = i - 1
        while(found == False and k >= 0):
            if (arr[k] == xPlusOne):
                found = True
                break
            k -= 1
 
        # if found is true, increment count
        if (found == True):
            count += 1
 
    return count
 
# Driver program
if __name__ == '__main__':
    arr = [1, 2, 3]
    n = len(arr)
 
    # call countElements function on array
    print(countElements(arr, n))
 
# This code is contributed by Surendra_Gangwar


C#
// C# program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
using System;
 
class GFG{
     
    // Function to find the countElements
    static int countElements(int[] arr, int n)
    {
        // Initialize count as zero
        int count = 0;
     
        // Iterate over each element
        for (int i = 0; i < n; i++) {
     
            // Store element in int x
            int x = arr[i];
     
            // Calculate x + 1
            int xPlusOne = x + 1;
     
            // Initialize found as false
            bool found = false;
     
            // Run loop to search for x + 1
            // after the current element
            for (int j = i + 1; j < n; j++) {
                if (arr[j] == xPlusOne) {
                    found = true;
                    break;
                }
            }
     
            // Run loop to search for x + 1
            // before the current element
            for (int k = i - 1;
                !found && k >= 0; k--) {
                if (arr[k] == xPlusOne) {
                    found = true;
                    break;
                }
            }
     
            // if found is true,
            // increment count
            if (found == true) {
                count++;
            }
        }
     
        return count;
    }
     
    // Driver program
    static public void Main ()
    {
        int[] arr = { 1, 2, 3 };
        int n = arr.Length;
     
        // call countElements function on array
        Console.WriteLine(countElements(arr, n));
 
    }
}
 
// This code is contributed by shubhamsingh10


Javascript


C++
// C++ program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
 
#include 
using namespace std;
 
// Function to find the countElements
int countElements(vector& arr)
{
    int size = arr.size();
 
    // Initialize result as zero
    int res = 0;
 
    // Create map
    map dat;
 
    // First loop to fill the map
    for (int i = 0; i < size; ++i) {
        dat[arr[i] - 1] = true;
    }
 
    // Second loop to check the map
    for (int i = 0; i < size; ++i) {
        if (dat[arr[i]] == true) {
            res++;
        }
    }
    return res;
}
 
// Driver program
int main()
{
    // Input Array
    vector arr = { 1, 3, 2, 3, 5, 0 };
 
    // Call the countElements function
    cout << countElements(arr) << endl;
 
    return 0;
}


Java
// Java program to count of elements
// A[i] such that A[i] + 1 is 
// also present in the Array
import java.util.*;
 
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Map dat = new HashMap<>();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       dat.put((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.containsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    System.out.println(countElements(arr));
     
}
}
 
// This code is contributed by shad0w1947


Python3
# Python program to count of elements
# A[i] such that A[i] + 1
# is also present in the Array
 
# Function to find the countElements
def countElements(arr):
     
    size = len(arr)
     
    # Initialize result as zero
    res = 0
     
    # Create map
    dat={}
     
    # First loop to fill the map
    for i in range(size):
        dat[arr[i] - 1] = True
         
    # Second loop to check the map
    for i in range(size):
        if (arr[i] in dat):
            res += 1
     
    return res
 
# Driver program
 
# Input Array
arr =  [1, 3, 2, 3, 5, 0]
 
# Call the countElements function
print(countElements(arr))
 
# This code is contributed by shubhamsingh10


C#
// C# program to count of elements
// A[i] such that A[i] + 1 is
// also present in the Array
using System;
using System.Collections.Generic;
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.Length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Dictionary dat = new Dictionary();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       if(!dat.ContainsKey(arr[i] - 1))
          dat.Add((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.ContainsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void Main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    Console.WriteLine(countElements(arr));
}
}
 
// This code is contributed by 29AjayKumar


输出:
2

时间复杂度:在上述方法中,对于给定的元素,我们检查所有其他元素,因此时间复杂度为O(N*N) ,其中 N 不是元素。
辅助空间复杂度:在上述方法中,我们没有使用任何额外的空间,因此辅助空间复杂度为O(1)
方法二:使用地图

  • 对于数组中的所有元素,比如 x,将 x-1 添加到映射中
  • 同样,对于数组中的所有元素,比如 x,检查它是否存在于映射中。如果存在,则增加计数器
  • 检查映射中的所有键后返回总计数

下面是上述方法的实现:

C++

// C++ program to count of elements
// A[i] such that A[i] + 1
// is also present in the Array
 
#include 
using namespace std;
 
// Function to find the countElements
int countElements(vector& arr)
{
    int size = arr.size();
 
    // Initialize result as zero
    int res = 0;
 
    // Create map
    map dat;
 
    // First loop to fill the map
    for (int i = 0; i < size; ++i) {
        dat[arr[i] - 1] = true;
    }
 
    // Second loop to check the map
    for (int i = 0; i < size; ++i) {
        if (dat[arr[i]] == true) {
            res++;
        }
    }
    return res;
}
 
// Driver program
int main()
{
    // Input Array
    vector arr = { 1, 3, 2, 3, 5, 0 };
 
    // Call the countElements function
    cout << countElements(arr) << endl;
 
    return 0;
}

Java

// Java program to count of elements
// A[i] such that A[i] + 1 is 
// also present in the Array
import java.util.*;
 
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Map dat = new HashMap<>();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       dat.put((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.containsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    System.out.println(countElements(arr));
     
}
}
 
// This code is contributed by shad0w1947

蟒蛇3

# Python program to count of elements
# A[i] such that A[i] + 1
# is also present in the Array
 
# Function to find the countElements
def countElements(arr):
     
    size = len(arr)
     
    # Initialize result as zero
    res = 0
     
    # Create map
    dat={}
     
    # First loop to fill the map
    for i in range(size):
        dat[arr[i] - 1] = True
         
    # Second loop to check the map
    for i in range(size):
        if (arr[i] in dat):
            res += 1
     
    return res
 
# Driver program
 
# Input Array
arr =  [1, 3, 2, 3, 5, 0]
 
# Call the countElements function
print(countElements(arr))
 
# This code is contributed by shubhamsingh10

C#

// C# program to count of elements
// A[i] such that A[i] + 1 is
// also present in the Array
using System;
using System.Collections.Generic;
class GFG{
     
// Function to find the countElements
public static int countElements(int[] arr)
{
    int size = arr.Length;
     
    // Initialize result as zero
    int res = 0;
     
    // Create map
    Dictionary dat = new Dictionary();
     
    // First loop to fill the map
    for(int i = 0; i < size; ++i)
    {
       if(!dat.ContainsKey(arr[i] - 1))
          dat.Add((arr[i] - 1), true);
    }
     
    // Second loop to check the map
    for(int i = 0; i < size; ++i)
    {
       if (dat.ContainsKey(arr[i]) == true)
       {
           res++;
       }
    }
    return res;
}
     
// Driver code
public static void Main(String[] args)
{
         
    // Input Array
    int[] arr = { 1, 3, 2, 3, 5, 0 };
     
    // Call the countElements function
    Console.WriteLine(countElements(arr));
}
}
 
// This code is contributed by 29AjayKumar
输出:
3

时间复杂度:在上述方法中,我们对数组进行了两次迭代。一次用于填充地图,第二次用于检查地图中的元素,因此时间复杂度为O(N) ,其中 N 为无元素。
辅助空间复杂度:在上述方法中,我们使用了一个可以包含 N 个元素的附加映射,因此辅助空间复杂度为O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live