通过将两个 0 或两个 1 对替换为 0 并将 10 或 01 对替换为 1 来减少二进制数组
给定一个大小为N的二进制数组arr[] ,任务是在执行一组操作后找到数组中剩余的最后一个数。在每个操作中,选择任意两个数字并执行以下操作:
- 如果两个数字相同,则将它们从数组中删除并插入0 。
- 如果两个数字不同,则删除它们并插入1 。
例子:
Input: arr[]={0, 0, 1}
Output: 1
Explanation: There are two possible sequence of operations as follows:
- arr[] = {0, 0, 1}, delete (0, 1) and insert 0 => arr[] = {0, 0}, delete (0, 0) and insert 1=> arr[] = {1}.
- arr[] = {0, 0, 1}, delete (0, 0) and insert 0 => arr[] = {0, 1}, delete (0, 1) and insert 1=> arr[] = {1}.
Hence the remaining element is 1.
Input: arr[]={1, 0, 0, 0, 1}
Output: 0
方法:可以根据以下观察解决给定的问题:
- 2 个相同的数字被 0 取代。
- 2 个不同的数字被 1 取代。
现在,为每个结果创建一个表:
仔细观察上表,可以注意到该表表示的是按位异或运算。因此,剩余的整数将等于给定数组元素的按位异或,可以进一步简化为 1 的频率为偶数,结果为0 ,否则为1 。
下面是上述方法的实现。
C++
// C++ program of the above approach
#include
using namespace std;
// Function to find last remaining
// integer in the given array
int lastNumber(vector& arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
for (int x : arr) {
if (x == 1) {
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
int main()
{
vector arr = { 1, 0, 0, 0, 1 };
cout << lastNumber(arr);
}
Java
// Java program of the above approach
import java.util.ArrayList;
class GFG {
// Function to find last remaining
// integer in the given array
static Integer lastNumber(ArrayList arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
for (int x : arr) {
if (x == 1) {
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
public static void main(String args[]) {
ArrayList arr = new ArrayList();
arr.add(1);
arr.add(0);
arr.add(0);
arr.add(0);
arr.add(1);
System.out.println(lastNumber(arr));
}
}
// This code is contributed by gfgking
Python3
# python program of the above approach
# Function to find last remaining
# integer in the given array
def lastNumber(arr):
# Variable to store the
# frequency of 1
one = 0
# Loop to iterate the
# given array
for x in arr:
if (x == 1):
one += 1
# If frequency of 1 is even
if (one % 2 == 0):
return 0
# If frequency of 1 is odd
return 1
# Driver Code
if __name__ == "__main__":
arr = [1, 0, 0, 0, 1]
print(lastNumber(arr))
# This code is contributed by rakeshsahni
C#
// C# program of the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find last remaining
// integer in the given array
static int lastNumber(List arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
foreach(int x in arr)
{
if (x == 1)
{
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
public static void Main()
{
List arr = new List(){ 1, 0, 0, 0, 1 };
Console.WriteLine(lastNumber(arr));
}
}
// This code is contributed by ukasp
Javascript
输出
0
时间复杂度: O(N)
辅助空间: O(1)