Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Subscribe to see which companies asked this question

利用XOR运算,原文地址:https://oj.leetcode.com/discuss/6170/my-o-n-solution-using-xor

因为A XOR A = 0,且XOR运算是可交换的,于是,对于实例{2,1,4,5,2,4,1}就会有这样的结果:

(2^1^4^5^2^4^1) => ((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5

就把只出现了一次的元素(其余元素均出现两次)给找出来了!

主要利用异或算法 ,就是相同的数异或是0,0与任意个数进行异或还是原来的数

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        //int result =0;
        //for(int i=0;i<nums.size();i++)
        //{
        //    result^=nums[i];
       // }
        //return result;
      
    }
};

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[] = { 1, 2, 1, 2, 4, 6, 7, 4, 6 };
	int len = sizeof(a) / sizeof(a[0]);
	int temp;
	int j;
	//1
	//for (int i = 0; i < len; i++)
	//{
	//	for ( j = 0; j < len; j++)
	//	{
	//		if (i == j)
	//			continue;
	//		if (a[i] == a[j])
	//			break;
	//	}
	//	if (j == len)
	//		temp = a[i];
	//}
	//2
	//sort(a, a + len);
	//for (int i = 0; i < len; i += 2)
	//{
	//	if (a[i] != a[i + 1])
	//		temp = a[i];
	//}

	//3

	/*temp = a[0];
	for (int i = 1; i < len; i++)
	{
		temp = temp ^ a[i];

	}
*/



	cout << temp;
	

	system("pause");
	return 0;
}


你可能感兴趣的:(Single Number)