【Leetcode】: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?
首先想到的方法是遍历,依次将每个元素同所有的元素比较,若只出现一次,则将该元素打印出来。写完程序之后发现运行时间过长,于是要改进算法。
改进后的算法依次将每个元素同剩下的元素相比较,若找到一样的则将这个元素与最后一个元素交换,若找不到一样的则打印该元素。
改进后的算法依然运行时间过长。于是想到利用异或的方法:将每个元素依次异或,最终结果即为只出现一次的元素。
a^b^c^a^b=a^a^b^b^c=(a^a)(b^b)^c=c.
public class Solution {
public static int singleNumber(int[] A) {
int t=A[0];
for(int i=1;i<A.length;i++) {
t=t^A[i];
}
return t;
}
}