博文中会简要介绍Leetcode P0136题目分析及解题思路。
“Single Number”这道题比较简单,可以用HashTable来完成,也可以通过位运算的技巧,由于两个相同的数异或后的结果是0,所以把所有数都异或以后,唯一的那个数就会剩下。
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?
以下是Java的题解代码实现。
class Solution {
public int singleNumber(int[] nums) {
int single = nums[0];
for (int idx=1; idx<nums.length; ++idx)
single ^= nums[idx];
return single;
}
}
以下是C++的题解代码实现。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int single = nums[0];
for (int idx=1; idx<nums.size(); ++idx)
single ^= nums[idx];
return single;
}
};