Single Number
描述:Single Number
Given a non-empty array of integers, ever element appears twice except for one. Find that single one
Note:
Your algorithm should have linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
OutPut: 1
Example 2:
Input: [4,1,2,1,2]
OutPut: 2
函数方法给出:
int SinlgeNumber(int* Nums, int NumsSize){}
01 普通方法 时间复杂度为 O(n^2)
使用双重for循环遍历数组,
记录每一个元素重复出现的次数,
如果出现的次数等于1的话就返回该元素
int SinlgeNumber(int* Nums, int NumsSize)
{
for (int i = 0; i < NumsSize; i++)
{
int count = 0;
for (int j = 0; j < NumsSize; j++)
{
if (Nums[i] == Nums[j])
{
count++;
}
}
if (count == 1)
{
return Nums[i];
}
}
return -1;
}
02 满足题目要求的方法 时间复杂度为 O(1)
使用位运算–>异或 XOR
异或: 相同为0, 不同为1
异或特点:
使用 异或运算 XOR
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
1) A ^ A = 0
2) A ^ 0 = 1
3) A ^ B = B ^ A (交换律)3 ^ 2 = 2 ^ 3
题目给的:2, 2, 1 可以使用交换律 最后的返回结果为 1
4,1,2,1,2 可以使用交换律 最后的返回结果为4
int SinlgeNumber(int* Nums, int NumsSize)
{
int n = Nums[0];
for(int i = 1; i < NumsSize; i++)
{
//n = n ^ Nums[i];
n ^= Nums[i];
}
return n;
}
源代码:
// Single Number
// Given a non-empty array of integers, ever element appears twice except for one.
// Find that single one
// Note:
// Your algorithm should have linear runtime complexity. Could you implement it without using extra memory?
// Example 1:
// Input: [2,2,1]
// OutPut: 1
// Example 2:
// Input: [4,1,2,1,2]
// OutPut: 2
#include <iostream>
#include <stdio.h>
using namespace std;
// 方法1
//-----------------------------------O(n^2)
/*int SinlgeNumber(int* Nums, int NumsSize)
{
for (int i = 0; i < NumsSize; i++)
{
int count = 0;
for (int j = 0; j < NumsSize; j++)
{
if (Nums[i] == Nums[j])
{
count++;
}
}
if (count == 1)
{
return Nums[i];
}
}
return -1;
}
*/
//-----------------------------------O(1)
int SinlgeNumber(int* Nums, int NumsSize)
{
// 使用 异或运算 XOR
// 0 ^ 0 = 0
// 0 ^ 1 = 1
// 1 ^ 0 = 1
// 1 ^ 1 = 0
// 1) A ^ A = 0
// 2) A ^ 0 = 1
// 3) A ^ B = B ^ A
int n = Nums[0];
for (int i = 1; i < NumsSize; i++)
{
n ^= Nums[i];
}
return n;
// 4,1,2,1,2
// 使用交换律
// 4,1,2,1,2 --> 1,4,2,1,2 --> 1,2,4,1,2 --> 1,2,1,4,2 --> 1,2,1,2,4
// 变成: 1,1,2,2,4
// 异或一下 等于 4
}
int main(int argc, char* argv[] )
{
int Nums1[] = { 4,1,2,1,2 };
int NumsSize = sizeof(Nums1) / sizeof(Nums1[0]);
int result = SinlgeNumber(Nums1, NumsSize);
cout << result << endl;
int Nums2[] = { 5,2,9,6,5,9,2,3,3};
NumsSize = sizeof(Nums2) / sizeof(Nums2[0]);
result = SinlgeNumber(Nums2, NumsSize);
cout << result << endl;
// 4,2,1,2,1 XOR 2 ^ 2 = 0, 1 ^ 1 = 0
// 4:0000 1000
// 1: 0000 0010 与前面异或结果--0000 1010
// 2: 0000 0001 与前面异或结果--0000 1011
// 1: 0000 0010 与前面异或结果--0000 1001
// 2: 0000 0001 与前面异或结果--0000 1000
return 0;
}