Leetcode-Number of occurrences of numbers in the array-2

Number of occurrences of numbers in the array

The question requires
  that except for two numbers in an integer array nums, other numbers appear twice. Please write a program to find these two numbers that only appear once. The required time complexity is O(n), and the space complexity is O(1).
The idea
  is based on the two formulas of a ^ a = 0 and 0 ^ a = a. We first XOR all the elements in the array. The binary result must be the result of two separate digits, and one bit of binary is selected as 1. , XOR the total elements of the array with the bits, the result is 1 into one group, and the result is 0 into one group, so the classification is destined to divide two separate numbers into two different groups, Then XOR the elements in each group, and the remaining values ​​in each group are individual numbers.
Code

int* singleNumbers(int* nums, int numsSize, int* returnSize)
{
	int *res = (int *)malloc(sizeof(int)* 2);
	*returnSize = 2;
	if (numsSize == 2)
	{
		return nums;
	}
	int s = 0;
	for (int i = 0; i < numsSize; i++)
	{
		s ^= nums[i];
	}
	//n 是计数这两个数哪一位不同
	int n = 0;
	while ((s & 1) == 0)
	{
		s = s >> 1;
		n++;
	}
	int s1 = 0;
	int s2 = 0;
	for (int i = 0; i < numsSize; i++)
	{
		if ((nums[i] >> n) & 1)
		{
			s1 ^= nums[i];
		}
		else
		{
			s2 ^= nums[i];
		}
	}
	res[0] = s1;
	res[1] = s2;
	return res;
}

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/113100980