题目意思:
一个数值数组中,大部分的数值出现两次,只有一个数值只出现过一次,求编程求出该数字。
要求,时间复杂度为线性,空间复杂度为O(1).
解题思路:
1.先排序,后查找。
由于排序的最快时间是O(nlogn), 所以这种方法不能满足时间的要求。
2.其它技巧来解决:
根据基本的计算机组成原理的知识,采用”异或运算“来巧妙的完成,
异或运算很简单:
0^0=0
1^1=0
1^0=0^1=1
也就是说相同则为0,不同则为1.
所以任何相同的两个数的异或运算值结果为0。
0与任何数进行异或运算等于该值。
所以,我们只需要将所有的数字进行异或运算一次(O(N)),它的结果就是我们要找的,只出现过一次的值。
#include
#include
using namespace std; //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? class Solution { public: int singleNumber(vector
& nums) { vector
::iterator it; it=nums.begin(); int sum=*it; for (it=nums.begin()+1;it
nums; std::vector
::iterator it; it = nums.begin(); int t; while(cin>>t) { it =nums.insert (it,t); } cout << instance.singleNumber(nums) << endl; return 0; }
?