可以使用C++程式碼檢查重新參與,以確保元素總和最多為x。
假設我們有兩個大小為n的陣列A和B,以及另一個數字x。我們必須檢查是否可以重新排列B中的元素,以便對於所有i(範圍為0到n-1),A[i] + B[i] <= x。
因此,如果輸入類似於A = [1, 2, 3];B = [1, 1, 2];x = 4,則輸出將為True,因為如果我們將B重新排列為[1, 2, 1],則和值將為1 + 1 <= 4,2 + 2 <= 4,以及3 + 1 <= 4。
步驟
為了解決這個問題,我們將遵循以下步驟:
n := size of A ans := 1 sum := 0 for initialize i := 0, when i < n, update (increase i by 1), do: sum := A[i] + B[n - i - 1] if sum > x, then: ans := 0 if ans is non-zero, then: return true Otherwise return false
示例
讓我們看看下面的實現,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
bool solve(vector<int> A, vector<int> B, int x){
int n = A.size();
int ans = 1;
int sum = 0;
for (int i = 0; i < n; ++i){
sum = A[i] + B[n - i - 1];
if (sum > x)
ans = 0;
}
if (ans)
return true;
else
return false;
}
int main(){
vector<int> A = { 1, 2, 3 };
vector<int> B = { 1, 1, 2 };
int x = 4;
cout << solve(A, B, x) << endl;
}輸入
{ 1, 2, 3 }, { 1, 1, 2 }, 4輸出
1
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP