C++中计算排序数组中乘积小于k的数对
给定一个排序的整型数组和一个整型变量x,任务是从给定数组中形成数对,计算数对中元素的乘积,并检查计算出的乘积是否小于k。
输入
int arr[] = {2, 7, 1, 0, 8}, int k = 10
输出
Count of pairs in a sorted array whose product is less than k are: 7
解释
The pairs that can be formed from the given array are: (2, 7) = 14(greater than k), (2, 1) = 2(less than k), (2, 0) = 0(less than k), (2, 8) = 16(greater than k), (7, 1) = 7(less than k), (7, 0) = 0(less than k), (7, 8) = 56(greater than k), (1, 0) = 0(less than k), (1, 8) = 8(less than k), (0, 8) = 0(less than k). So, the count of pairs with sum less than k are 7.
输入
int arr[] = {2, 4, 6, 8}, int k = 10
输出
Count of pairs in a sorted array whose product is less than k are: 1
解释
The pairs that can be formed from the given array are: (2, 4) = 8(less than k), (2, 6) = 12(greater than k), (2, 8) = 16(greater than k), (4, 6) = 24(greater than x), (4, 8) = 32(greater than k), (6, 8) = 48(greater than k). So, the count of pairs with products less than k is 1.
下面程序中使用的算法如下:
解决给定问题有多种方法,即朴素方法和高效方法。所以让我们先看看朴素方法。
输入一个整型数组,计算数组大小,并将数据传递给函数。
声明一个临时变量count来存储乘积小于k的数对的数量。
从i=0开始循环到数组大小。
在循环内,从j=i+1开始另一个循环到数组大小。
在循环内计算乘积arr[i] * arr[j],如果乘积< k,则将count加1。
返回count。
打印结果。
高效方法
输入一个整型数组,计算数组大小,并将数据传递给函数。
声明一个临时变量count来存储和数小于x的数对的数量。
设置arr_0为0,arr_1为size-1。
从arr_0循环到arr_1。
在循环内,如果arr[arr_0] * arr[arr_1] < x,则设置count为count + (arr_1 - arr_0),并递增arr_0++,否则将arr_1减1。
返回count。
打印结果。
示例(朴素方法)
#include <iostream> using namespace std; int pair_product(int arr[], int size, int k){ int count = 0; int product = 1; for(int i = 0 ; i<size ; i++){ for(int j = i+1; j<size; j++){ product = arr[i] * arr[j]; if(product < k){ count++; } } } return count; } int main(){ int arr[] = {5, 8, 2, 1, 3}; int size = sizeof(arr) / sizeof(arr[0]); int k = 10; cout<<"Count of pairs in a sorted array whose product is less than k are: "<<pair_product(arr, size, k); return 0; }
输出
如果运行以上代码,将生成以下输出:
Count of pairs in a sorted array whose product is less than k are: 5
示例(高效方法)
#include <iostream> using namespace std; int pair_product(int arr[], int size, int k){ int arr_0 = 0; int arr_1 = size-1; int count = 0; int product = 1; while(arr_0 < arr_1){ product = arr[arr_0] * arr[arr_1]; if (product < k){ count = count + (arr_1 - arr_0); arr_0++; } else{ arr_1--; } } return count; } int main(){ int arr[] = {1, 3, 4, 2, 1}; int size = sizeof(arr) / sizeof(arr[0]); int k = 5; cout<<"Count of pairs in a sorted array whose product is less than k are: "<<pair_product(arr, size, k); return 0; }
输出
如果运行以上代码,将生成以下输出:
Count of pairs in a sorted array whose product is less than k are: 10
广告