找出兩個陣列中之和不在兩個陣列中的兩個數字的 C++ 程式
假設我們有兩個陣列 A,其中包含 n 個元素,以及 B,其中包含 m 個元素。從 A 中選擇某個元素 a 和從 B 中選擇某個元素 b,使得 a + b 不屬於 A 或 B。
因此,如果輸入如下所示 A = [3, 2, 2];B = [1, 5, 7, 7, 9],那麼輸出將為 [3, 1],因為 3 + 1 = 4 不存在於任何陣列中。(還有其他答案可能)
步驟
為了解決此問題,我們將按照以下步驟操作 -
sort the array A sort the array B return last element of A and last element of B
示例
讓我們看看以下實現以獲得更好的理解 -
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A, vector<int> B) { sort(A.begin(), A.end()); sort(B.begin(), B.end()); cout << A[A.size() - 1] << ", " << B[B.size() - 1]; } int main() { vector<int> A = { 3, 2, 2 }; vector<int> B = { 1, 5, 7, 7, 9 }; solve(A, B); }
輸入
{ 3, 2, 2 }, { 1, 5, 7, 7, 9 }
輸出
3, 9
廣告