C++程序:查找插入新元素后的数组,其中任意两个元素的差都在数组中
假设我们有一个包含n个不同元素的数组A。如果对于任意两个不同的元素B[i]和B[j],|B[i] - B[j]|至少在B中出现一次,并且B中的所有元素都不同,则称数组B为“优良”数组。我们需要检查是否可以向A中添加几个整数以使其成为大小最多为300的优良数组。如果可以,则返回新数组;否则,返回-1。
因此,如果输入类似于A = [4, 8, 12, 6],则输出将为[8, 12, 6, 2, 4, 10],因为|4−2| = |6−4| = |8−6| = |10−8| = |12−10| = 2在数组中,|6−2| = |8−4| = |10−6| = |12−8| = 4在数组中,|8−2| = |10−4| = |12−6| = 6在数组中,|10−2| = |12−4| = 8在数组中,|12−2| = 10在数组中,因此该数组是优良的。(其他答案也是可能的)
步骤
为了解决这个问题,我们将遵循以下步骤:
n := size of A t := 0 b := 0 for initialize i := 0, when i < n, update (increase i by 1), do: a := A[i] if a < 0, then: t := 1 b := maximum of a and b if t is non-zero, then: print -1 Otherwise for initialize i := 0, when i <= b, update (increase i by 1), do: print i
示例
让我们来看下面的实现以更好地理解:
#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A) {
int n = A.size();
int t = 0;
int b = 0;
for (int i = 0; i < n; i++) {
int a = A[i];
if (a < 0)
t = 1;
b = max(a, b);
}
if (t)
cout << "-1";
else {
for (int i = 0; i <= b; i++)
cout << i << ", ";
}
}
int main() {
vector<int> A = { 4, 8, 12, 6 };
solve(A);
}输入
{ 4, 8, 12, 6 }输出
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP