136. Single Number 提交了自己,别人是一行代码
leetcode吧
全部回复
仅看楼主
level 6
milk_bread 楼主
一个由于数字组成的数组,里面的数字除了一个都出现了两次。找到那个只有一个的数字。
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。如果这么算我难道不要排序么?
2018年11月23日 06点11分 1
level 6
milk_bread 楼主
我的问题想了一下 应该是 a^b^c^b^c 是否等于 b^b^c^c^a 也就是按位异或能不能交换顺序。 执行的结果是不是相同的。
2018年11月23日 06点11分 2
level 3
异或是符合交换律结合律的。
2019年06月29日 16点06分 3
1