Given an 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?
给定一个数组,每个元素都出现2次除了其中的一个,找出只出现一次的数字注意:算法必须是线性时间复杂度,可以不使用额外空间实现吗?
使用异或运算。
算法实现类
public class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length < 1) {
throw new IllegalArgumentException("nums");
}
for (int i = 1; i< nums.length; i++) {
nums[0] ^= nums[i];
}
return nums[0];
}
}
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
版权声明:本文为博主原创文章,未经博主允许不得转载。
【LeetCode-面试算法经典-Java实现】【136-Single Number(只出现一次的数字)】
原文地址:http://blog.csdn.net/derrantcm/article/details/47745389