📌  相关文章
📜  对于第一个数组中的每个元素,计算第二个数组中小于或等于它的元素 | 2套

📅  最后修改于: 2021-10-27 07:01:58             🧑  作者: Mango

给定两个未排序的数组 arr1[] 和 arr2[]。它们可能包含重复项。对于 arr1[] 中的每个元素,计算数组 arr2[] 中小于或等于它的元素。
例子

这个问题已经在上一篇文章中讨论过了。
解决方案:在本文中,讨论了针对上述问题的更优化的线性时间解决方案。此处讨论的方法适用于值在小范围内的数组。可用作数组索引的一系列值。

  • 方法 :
    这个想法是创建一个前缀映射到第二个数组的最大元素。 prefix 数组将存储直到该索引的最大元素,例如,prefix[i] 将存储直到 i 的元素计数。然后遍历第一个数组,从前缀数组中找出小于或等于该元素的元素个数。
    前缀数组是通过遍历前缀数组并通过添加宝贵元素更新当前元素来创建的,即prefix[i]+ =prefix[i-1]。
  • 算法:
    1. 创建第二个和第一个数组或映射的最大元素大小的额外空间(前缀)。
    2. 遍历第二个数组。
    3. 对于第二个数组的每个元素增加前缀数组的计数,即 prefix[arr2[i]]++
    4. 遍历前缀数组从 1 到 MAX(第二个和第一个数组的最大元素,并通过添加第 i-1 个元素的和来更新第 i 个元素
    5. 现在遍历第一个数组并打印 prefix[arr_1[i]] 的值
  • 执行:
C++
// C++ program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
 
#include 
using namespace std;
 
#define MAX 100000
 
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
void countEleLessThanOrEqual(int arr1[], int m,
                                int arr2[], int n)
{
    // Creating hash array initially
    // filled with zero
    int hash[MAX] = {0};
     
    // Insert element of arr2[] to hash
    // such that hash[i] will give count of
    // element i in arr2[]
    for (int i = 0; i < n; i++)
        hash[arr2[i]]++;
 
    // Presum of hash array
    // such that hash[i] will give count of
    // element less than or equals to i in arr2[]
    for (int i=1; i


Java
// Java program for each element
// in 1st array count elements
// less than or equal to it in
// 2nd array
import java.io.*;
 
class GFG
{
static int MAX = 100000;
 
// Function for each element
// in 1st array count elements
// less than or equal to it
// in 2nd array
static void countEleLessThanOrEqual(int arr1[], int m,
                                    int arr2[], int n)
{
    // Creating hash array initially
    // filled with zero
    int hash[] = new int[MAX];
     
    // Insert element of arr2[] to
    // hash such that hash[i] will
    // give count of element i in arr2[]
    for (int i = 0; i < n; i++)
        hash[arr2[i]]++;
 
    // Presum of hash array
    // such that hash[i] will
    // give count of element
    // less than or equals to
    // i in arr2[]
    for(int i = 1; i < MAX; i++)
    {
        hash[i] = hash[i] +
                  hash[i - 1];
    }
     
    // Traverse arr1[] and
    // print hash[arr[i]]
    for (int i = 0; i < m; i++)
    {
        System.out.print(hash[arr1[i]] + " ");
    }
}
 
// Driver code
public static void main (String[] args)
{
    int arr1[] = {1, 2, 3, 4, 7, 9};
    int arr2[] = {0, 1, 2, 1, 1, 4};
    int m, n;
     
    m = arr1.length;
    n = arr2.length;
     
    countEleLessThanOrEqual(arr1, m, arr2, n);
}
}
 
// This code is contributed
// by inder_verma


Python3
# Python 3 program for each element in 1st
# array count elements less than or equal
# to it in 2nd array
 
MAX = 100000
 
# Function for each element in 1st
# array count elements less than or
# equal to it in 2nd array
def countEleLessThanOrEqual(arr1, m, arr2, n):
     
    # Creating hash array initially
    # filled with zero
    hash = [0 for i in range(MAX)]
     
    # Insert element of arr2[] to hash
    # such that hash[i] will give count
    # of element i in arr2[]
    for i in range(n):
        hash[arr2[i]] += 1
 
    # Presum of hash array such that
    # hash[i] will give count of element
    # less than or equals to i in arr2[]
    for i in range(1, MAX, 1):
        hash[i] = hash[i] + hash[i - 1]
     
    # Traverse arr1[] and print hash[arr[i]]
    for i in range(m):
        print(hash[arr1[i]], end = " ")    
 
# Driver code
if __name__ == '__main__':
    arr1 = [1, 2, 3, 4, 7, 9]
    arr2 = [0, 1, 2, 1, 1, 4]
    m = len(arr1)
    n = len(arr2)
     
    countEleLessThanOrEqual(arr1, m, arr2, n)
     
# This code is contributed by
# Shashank_Sharma


C#
// C# program for each element
// in 1st array count elements
// less than or equal to it in
// 2nd array
using System;
public class GFG {
 
static int MAX = 100000;
 
// Function for each element
// in 1st array count elements
// less than or equal to it
// in 2nd array
static void countEleLessThanOrEqual(int []arr1, int m,
                                    int []arr2, int n)
{
    // Creating hash array initially
    // filled with zero
    int []hash = new int[MAX];
     
    // Insert element of arr2[] to
    // hash such that hash[i] will
    // give count of element i in arr2[]
    for (int i = 0; i < n; i++)
        hash[arr2[i]]++;
 
    // Presum of hash array
    // such that hash[i] will
    // give count of element
    // less than or equals to
    // i in arr2[]
    for(int i = 1; i < MAX; i++)
    {
        hash[i] = hash[i] +
                hash[i - 1];
    }
     
    // Traverse arr1[] and
    // print hash[arr[i]]
    for (int i = 0; i < m; i++)
    {
        Console.Write(hash[arr1[i]] + " ");
    }
}
 
// Driver code
public static void Main ()
{
    int []arr1 = {1, 2, 3, 4, 7, 9};
    int []arr2 = {0, 1, 2, 1, 1, 4};
    int m, n;
     
    m = arr1.Length;
    n = arr2.Length;
     
    countEleLessThanOrEqual(arr1, m, arr2, n);
}
}
 
// This code is contributed by Shikha Singh.


PHP


Javascript


C++
// C++ program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
#include 
#include 
#include 
 
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
void countLessThanOrEqual(const std::vector& vec1,
                        const std::vector& vec2) {
    std::map countOfVec2;
    for (const auto& item : vec2) {
        ++countOfVec2[item];
    }
 
    unsigned int prev = 0;
    for (auto& pair : countOfVec2) {
        pair.second += prev;
        prev = pair.second;
    }
    // Traverse arr1[] and print result
    for (const auto& item : vec1) {
        unsigned int result = (--countOfVec2.upper_bound(item))->second;
        std::cout << result << " ";
    }
}
 
// Driver code
int main()
{
    std::vector arr1 = { 1, 2, 3, 4, 7, 9 };
    std::vector arr2 = { 0, 1, 2, 1, 1, 4 };
 
    countLessThanOrEqual(arr1, arr2);
 
    return 0;
}


Java
// Java program for each element in 1st 
// array count elements less than or equal to it 
// in 2nd array
import java.util.*;
class GFG {
 
  // Function for each element in 1st 
  // array count elements less than or equal to it 
  // in 2nd array 
  static void countLessThanOrEqual(int vec1[], int vec2[])
  {
    HashMap countOfVec2 = new HashMap<>();  
    for(int item : vec2)
    {
      if(!countOfVec2.containsKey(item))
        countOfVec2.put(item, 0);
      countOfVec2.put(item, countOfVec2.get(item) + 1);
    }
 
    int prev = 0;
    Vector li = new Vector();
    for (Map.Entry pair : countOfVec2.entrySet())
    {
      li.add(pair.getKey());
    }
    for(int pair : li)
    {
      countOfVec2.put(pair, countOfVec2.get(pair) + prev);
      prev = countOfVec2.get(pair);
    }
 
    // Traverse arr1[] and print result 
    for(int item : vec1)
    {
      int i = 0, v = 0, last = 0;
      for (Map.Entry pair : countOfVec2.entrySet())
      {
        last = pair.getKey();
        if(item < pair.getKey())
        {
          v = i;
          break;
        }
        i++;
      }
      v -= 1;
      if(v == -1)
      {
        v = last;
      }
      int result = countOfVec2.get(v);
      System.out.print(result + " ");
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr1[] = {1, 2, 3, 4, 7, 9};
    int arr2[] = {0, 1, 2, 1, 1, 4};
 
    countLessThanOrEqual(arr1, arr2);
  }
}
 
// This code is contributed by divyesh072019.


Python3
# Python3 program for each element in 1st
# array count elements less than or equal to it
# in 2nd array
 
# Function for each element in 1st
# array count elements less than or equal to it
# in 2nd array
def countLessThanOrEqual(vec1, vec2):
     
    countOfVec2 = {}
    for item in vec2:
        if item not in countOfVec2:
            countOfVec2[item] = 0
        countOfVec2[item] += 1
         
    prev = 0
    for pair in countOfVec2:
        countOfVec2[pair] += prev
        prev = countOfVec2[pair]
         
    val = list(countOfVec2)
     
    # Traverse arr1[] and print result
    for item in vec1:
        i = 0
        v = 0
        for i in range(len(val)):
            if item < val[i]:
                v = i
                break
        v -= 1
        if v == -1:
            v = val[-1]
        result = countOfVec2[v]
        print(result, end = " ")
 
# Driver code
arr1 = [1, 2, 3, 4, 7, 9]
arr2 = [0, 1, 2, 1, 1, 4]
 
countLessThanOrEqual(arr1, arr2)
 
# This code is contributed by shubhamsingh10


C#
// C# program for each element in 1st 
// array count elements less than or equal to it 
// in 2nd array 
using System;
using System.Collections.Generic;  
class GFG {
 
  // Function for each element in 1st 
  // array count elements less than or equal to it 
  // in 2nd array 
  static void countLessThanOrEqual(int[] vec1, int[] vec2)
  {
    Dictionary countOfVec2 = new Dictionary(); 
    foreach(int item in vec2)
    {
      if(!countOfVec2.ContainsKey(item))
        countOfVec2[item] = 0;
      countOfVec2[item] += 1;
    }
 
    int prev = 0;
    List li = new List();
    foreach(KeyValuePair pair in countOfVec2)
    {
      li.Add(pair.Key);
    }
    foreach(int pair in li)
    {
      countOfVec2[pair] += prev;
      prev = countOfVec2[pair];
    }
 
    // Traverse arr1[] and print result 
    foreach(int item in vec1)
    {
      int i = 0, v = 0, last = 0;
      foreach(KeyValuePair pair in countOfVec2)
      {
        last = pair.Key;
        if(item < pair.Key)
        {
          v = i;
          break;
        }
        i++;
      }
      v -= 1;
      if(v == -1)
      {
        v = last;
      }
      int result = countOfVec2[v];
      Console.Write(result + " ");
    }
  }
 
  // Driver code       
  static void Main()
  {
    int[] arr1 = {1, 2, 3, 4, 7, 9};
    int[] arr2 = {0, 1, 2, 1, 1, 4};
 
    countLessThanOrEqual(arr1, arr2);
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript


输出:
4 5 5 6 6 6
  • 执行:

C++

// C++ program for each element in 1st
// array count elements less than or equal to it
// in 2nd array
#include 
#include 
#include 
 
// Function for each element in 1st
// array count elements less than or equal to it
// in 2nd array
void countLessThanOrEqual(const std::vector& vec1,
                        const std::vector& vec2) {
    std::map countOfVec2;
    for (const auto& item : vec2) {
        ++countOfVec2[item];
    }
 
    unsigned int prev = 0;
    for (auto& pair : countOfVec2) {
        pair.second += prev;
        prev = pair.second;
    }
    // Traverse arr1[] and print result
    for (const auto& item : vec1) {
        unsigned int result = (--countOfVec2.upper_bound(item))->second;
        std::cout << result << " ";
    }
}
 
// Driver code
int main()
{
    std::vector arr1 = { 1, 2, 3, 4, 7, 9 };
    std::vector arr2 = { 0, 1, 2, 1, 1, 4 };
 
    countLessThanOrEqual(arr1, arr2);
 
    return 0;
}

Java

// Java program for each element in 1st 
// array count elements less than or equal to it 
// in 2nd array
import java.util.*;
class GFG {
 
  // Function for each element in 1st 
  // array count elements less than or equal to it 
  // in 2nd array 
  static void countLessThanOrEqual(int vec1[], int vec2[])
  {
    HashMap countOfVec2 = new HashMap<>();  
    for(int item : vec2)
    {
      if(!countOfVec2.containsKey(item))
        countOfVec2.put(item, 0);
      countOfVec2.put(item, countOfVec2.get(item) + 1);
    }
 
    int prev = 0;
    Vector li = new Vector();
    for (Map.Entry pair : countOfVec2.entrySet())
    {
      li.add(pair.getKey());
    }
    for(int pair : li)
    {
      countOfVec2.put(pair, countOfVec2.get(pair) + prev);
      prev = countOfVec2.get(pair);
    }
 
    // Traverse arr1[] and print result 
    for(int item : vec1)
    {
      int i = 0, v = 0, last = 0;
      for (Map.Entry pair : countOfVec2.entrySet())
      {
        last = pair.getKey();
        if(item < pair.getKey())
        {
          v = i;
          break;
        }
        i++;
      }
      v -= 1;
      if(v == -1)
      {
        v = last;
      }
      int result = countOfVec2.get(v);
      System.out.print(result + " ");
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr1[] = {1, 2, 3, 4, 7, 9};
    int arr2[] = {0, 1, 2, 1, 1, 4};
 
    countLessThanOrEqual(arr1, arr2);
  }
}
 
// This code is contributed by divyesh072019.

蟒蛇3

# Python3 program for each element in 1st
# array count elements less than or equal to it
# in 2nd array
 
# Function for each element in 1st
# array count elements less than or equal to it
# in 2nd array
def countLessThanOrEqual(vec1, vec2):
     
    countOfVec2 = {}
    for item in vec2:
        if item not in countOfVec2:
            countOfVec2[item] = 0
        countOfVec2[item] += 1
         
    prev = 0
    for pair in countOfVec2:
        countOfVec2[pair] += prev
        prev = countOfVec2[pair]
         
    val = list(countOfVec2)
     
    # Traverse arr1[] and print result
    for item in vec1:
        i = 0
        v = 0
        for i in range(len(val)):
            if item < val[i]:
                v = i
                break
        v -= 1
        if v == -1:
            v = val[-1]
        result = countOfVec2[v]
        print(result, end = " ")
 
# Driver code
arr1 = [1, 2, 3, 4, 7, 9]
arr2 = [0, 1, 2, 1, 1, 4]
 
countLessThanOrEqual(arr1, arr2)
 
# This code is contributed by shubhamsingh10

C#

// C# program for each element in 1st 
// array count elements less than or equal to it 
// in 2nd array 
using System;
using System.Collections.Generic;  
class GFG {
 
  // Function for each element in 1st 
  // array count elements less than or equal to it 
  // in 2nd array 
  static void countLessThanOrEqual(int[] vec1, int[] vec2)
  {
    Dictionary countOfVec2 = new Dictionary(); 
    foreach(int item in vec2)
    {
      if(!countOfVec2.ContainsKey(item))
        countOfVec2[item] = 0;
      countOfVec2[item] += 1;
    }
 
    int prev = 0;
    List li = new List();
    foreach(KeyValuePair pair in countOfVec2)
    {
      li.Add(pair.Key);
    }
    foreach(int pair in li)
    {
      countOfVec2[pair] += prev;
      prev = countOfVec2[pair];
    }
 
    // Traverse arr1[] and print result 
    foreach(int item in vec1)
    {
      int i = 0, v = 0, last = 0;
      foreach(KeyValuePair pair in countOfVec2)
      {
        last = pair.Key;
        if(item < pair.Key)
        {
          v = i;
          break;
        }
        i++;
      }
      v -= 1;
      if(v == -1)
      {
        v = last;
      }
      int result = countOfVec2[v];
      Console.Write(result + " ");
    }
  }
 
  // Driver code       
  static void Main()
  {
    int[] arr1 = {1, 2, 3, 4, 7, 9};
    int[] arr2 = {0, 1, 2, 1, 1, 4};
 
    countLessThanOrEqual(arr1, arr2);
  }
}
 
// This code is contributed by divyeshrabadiya07.

Javascript


输出:
4 5 5 6 6 6
  • 复杂度分析:
    • 时间复杂度: O(max + n ) 其中 max 是两个数组的最大元素,n 是数组的长度。
      需要对数组和前缀数组进行一次遍历。
    • 空间复杂度: O(max) 其中 max 是两个数组的最大元素。
      需要一个大小为 max 的前缀数组。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程