您的位置:首页 > 编程语言 > Java开发

Leetcode Single Number

2015-05-12 18:19 387 查看

题目:

Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear run time complexity. Could you implement it without using extra memory?

分析:

这道题既用线性的时间复杂度也不用额外的存储空间,使用一个技巧,位异或。如果数是成对出现的,那么它们的异或结果是0,而任何数和0按位异或的结果是它本身。走一趟最后所有数的异或结果就是这个单独出现的数。

Java代码实现:

public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for(int i=0;i<nums.length;i++)
result = result ^ nums[i];

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息