136. Single Number
Problem:
Given a non-empty 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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
思路1:
首先将数组排序,然后判断每个数与前后是否都不相等,如果都不相等则返回。注意首尾的值单独拿出来比较。
Solution I:
int singleNumber(vector<int>& nums) {
int n = nums.size();
if (n == 1) return nums[0];
sort(nums.begin(), nums.end());
if (nums[0] != nums[1]) return nums[0];
for (int i = 1; i < n-2; i++) {
if (nums[i] != nums[i-1] && nums[i] != nums[i+1])
return nums[i];
}
return nums[n-1];
}
性能:
Runtime: 24 ms Memory Usage: 9.9 MB
思路2:
利用异或的性质:a XOR a = 0,而且异或操作具有可交换性,所以将数组中所有元素进行XOR操作后,剩下的数即为单一的数。
Solution II:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int i = 0; i < nums.size(); i++)
ans ^= nums[i];
return ans;
}
性能:
Runtime: 12 ms Memory Usage: 9.8 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。