Given an array of integers, every element appears twice except for one. Find that single one.
Note:
our algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
题目意思:
一个整型数组中,每个整数都出现过两次,除了一个整数,请在线性时间复杂度O(n)和空间复杂度T(1)内找出这个整数。
分析:这个题目关键在于要控制时间复杂度为O(n)和空间复杂度;
每个整数都出现2次,假想可以把它们互相相减,最后剩下的结果就是仅出现一次的整数;但实际上不能直接相减,不过可以通过别的运算让两个相同的整数经过运算变成0,即通过异或^运算:相同为0,相异为1。
思路想清楚了,具体代码很简单,如下。
public class Solution {
public int singleNumber(int[] nums) {
int i=0;
int result=0;
while(i<nums.length){
//数组中元素不断的做异或运算
result=result^nums[i];
i++;
}
return result;
}
}
[LeetCode-136]Single Number(java)
最新推荐文章于 2018-10-23 21:08:30 发布