LeetCode 136. Single Number
Posted Xycdada
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 136. Single Number相关的知识,希望对你有一定的参考价值。
136. Single Number
- Total Accepted: 173470
- Total Submissions: 331880
- Difficulty: Easy
- Contributors: Admin
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
题意:给你一个动态数组,里面的数只有一个数出现过一次其余的数都出现过两次,让你在不另辟空间的情况下用O(n)的复杂度实现,真是神奇的算法,能想到的也只有快排那些O(n*lgn)的东西
实现:因为A和A的异或等于0,而A和0的异或等于A,所以将整个数组遍历每个数异或一遍的结果就是要找的那个数,是不是很神奇
class Solution {
public:
int singleNumber(vector<int>& nums) {
int i = 1;
while(i<nums.size())
{
nums[i]=nums[i-1]^nums[i];
i++;
}
return nums[i-1];
}
};
public:
int singleNumber(vector<int>& nums) {
int i = 1;
while(i<nums.size())
{
nums[i]=nums[i-1]^nums[i];
i++;
}
return nums[i-1];
}
};
以上是关于LeetCode 136. Single Number的主要内容,如果未能解决你的问题,请参考以下文章