首页 > 代码库 > LeetCode 136. Single Number
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。