企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# 要添加的元素,以便数组中存在某个范围的所有元素 > 原文: [https://www.geeksforgeeks.org/elements-to-be-added-so-that-all-elements-of-a-range-are-present-in-array/](https://www.geeksforgeeks.org/elements-to-be-added-so-that-all-elements-of-a-range-are-present-in-array/) 给定大小为 N 的数组。令 A 和 B 分别为数组中的最小值和最大值。 任务是查找应将给定数组添加多少个数字,以使[A,B]范围内的所有元素在数组中至少出现一次。 **示例**: ``` Input : arr[] = {4, 5, 3, 8, 6} Output : 1 Only 7 to be added in the list. Input : arr[] = {2, 1, 3} Output : 0 ``` **方法 1(排序)** 1-对数组进行排序。 2-比较 arr [i] == arr [i + 1] -1。 如果不是,则更新计数= arr [i + 1] -arr [i] -1。 3-返回计数。 ## C++ ```cpp // C++ program for above implementation #include <bits/stdc++.h> using namespace std; // Function to count numbers to be added int countNum(int arr[], int n) {     int count = 0;     // Sort the array     sort(arr, arr + n);     // Check if elements are consecutive     //  or not. If not, update count     for (int i = 0; i < n - 1; i++)         if (arr[i] != arr[i+1] &&              arr[i] != arr[i + 1] - 1)             count += arr[i + 1] - arr[i] - 1;     return count; } // Drivers code int main() {     int arr[] = { 3, 5, 8, 6 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << countNum(arr, n) << endl;     return 0; } ```