📌  相关文章
📜  追加两个元素以使数组满足给定条件

📅  最后修改于: 2021-05-25 04:34:50             🧑  作者: Mango

给定非负整数的数组arr [] ,让我们将X定义为所有数组元素的XOR,将S定义为所有数组元素的总和。任务是找到两个元素,以便在将它们附加到数组后,对更新后的数组满足S = 2 * X。

例子:

天真的方法:运行两个从1S的嵌套循环,并检查每对是否满足条件。这将花费O(S 2 )时间。
高效方法:可以观察到,如果将XS + 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现场课程美国》。