leetcode吧 关注:1,089贴子:2,335
  • 4回复贴,共1

136. Single Number 提交了自己,别人是一行代码

只看楼主收藏回复

一个由于数字组成的数组,里面的数字除了一个都出现了两次。找到那个只有一个的数字。
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
我想象就像打扑克牌,排序一样。从里面找相同的放在一起。换位置。于是写了如下的方法。
public int SingleNumber(int[] nums) {
for (int i = nums.Length - 1; i >= 0; i--)
{
if (i % 2 != 0) return nums[i + 1];
for (int j = i - 1; j >= 0; j--)
{
if (nums[j] == nums[i])
{
nums[j] = nums[i - 1];
nums[i - 1] = nums[i];
i = i - 1;
break;
}
}
}
return nums[0];
}
提交被accept以后 Your runtime beats 7.09 % of csharp submissions
然后点前面人的一看。哇靠就一行。震惊了。但是不太明白这种二进制的位运算。
public int SingleNumber(int[] nums) {
return nums.Aggregate( (x, y) => x ^ y);
}
重学一下^ 就是如果两个数二进制的相同(1同1 0同0)那么按位异或就是零。不同才是1。如果这么算我难道不要排序么?


IP属地:上海1楼2018-11-23 14:16回复
    我的问题想了一下 应该是 a^b^c^b^c 是否等于 b^b^c^c^a 也就是按位异或能不能交换顺序。 执行的结果是不是相同的。


    IP属地:上海2楼2018-11-23 14:22
    回复
      异或是符合交换律结合律的。


      IP属地:陕西3楼2019-06-30 00:05
      回复