给定非负整数的数组arr [] ,让我们将X定义为所有数组元素的XOR,将S定义为所有数组元素的总和。任务是找到两个元素,以便在将它们附加到数组后,对更新后的数组满足S = 2 * X。
例子:
Input: arr[] = {1, 7}
Output: 6 14
Initially S = 8, and X = 6. After appending 6
and 14, S_NEW = (8 + 6 + 14) = 28
and X_NEW = (6 ^ 6 ^ 14) = 14
Clearly, S_NEW = 2 * X_NEW
Input: arr[] = {1, 3}
Output: 2 6
天真的方法:运行两个从1到S的嵌套循环,并检查每对是否满足条件。这将花费O(S 2 )时间。
高效方法:可以观察到,如果将X和S + X附加到数组,则满足给定条件的S_NEW = 2 *(S + X)和X_NEW = S +X 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the required numbers
void findNums(int arr[], int n)
{
// Find the sum and xor
int S = 0, X = 0;
for (int i = 0; i < n; i++) {
S += arr[i];
X ^= arr[i];
}
// Print the required elements
cout << X << " " << (X + S);
}
// Driver code
int main()
{
int arr[] = { 1, 7 };
int n = sizeof(arr) / sizeof(int);
findNums(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to find the required numbers
static void findNums(int arr[], int n)
{
// Find the sum and xor
int S = 0, X = 0;
for (int i = 0; i < n; i++)
{
S += arr[i];
X ^= arr[i];
}
// Print the required elements
System.out.println(X + " " + (X + S));
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1, 7 };
int n = arr.length;
findNums(arr, n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to find the required numbers
def findNums(arr, n) :
# Find the sum and xor
S = 0; X = 0;
for i in range(n) :
S += arr[i];
X ^= arr[i];
# Print the required elements
print(X, X + S);
# Driver code
if __name__ == "__main__" :
arr = [ 1, 7 ];
n = len(arr);
findNums(arr, n);
# This code is contributed by AnkiRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the required numbers
static void findNums(int []arr, int n)
{
// Find the sum and xor
int S = 0, X = 0;
for (int i = 0; i < n; i++)
{
S += arr[i];
X ^= arr[i];
}
// Print the required elements
Console.WriteLine(X + " " + (X + S));
}
// Driver code
public static void Main()
{
int []arr = { 1, 7 };
int n = arr.Length;
findNums(arr, n);
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
6 14
时间复杂度: O(n)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。