136. Single Number
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?
题意:
一组数组,所有的数字都是成对出现的,只有一个数字是单独出现的,找到单独出现的数组
空间复杂度要求为常数,时间复杂度为线性
算法思路:
异或操作的原理是相同的数为0,不同的数为其本书,所有把所有的数依次按位异或,最终剩下的数就是单独的那个数
代码:
package easy;
public class SingleNumber {
public int singleNumber(int[] nums) {
int result = 0;
for(int i=0; i<nums.length; i++){
result ^= nums[i];
}
return result;
}
public static void main(String[] args){
System.out.println(3^1);
}
}