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