Single Number

来源:互联网 发布:轻淘宝设置pid 编辑:程序博客网 时间:2024/06/05 23:39

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? 



o(n)的算法只能是线性扫描一遍,可能的相法是位运算。对于异或来说:

1. 异或运算是可交换,即 a ^ b = b ^ a

2. 0 ^ a = a

那么如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....,可以将所有相同元素交换至相邻位置,首先运算相同元素,则会产生(n - 1)/2个0异或积,剩余一个单一元素,他们的异或积为这个单一元素自己,得解。


public class Solution {public int singleNumber(int[] A) {if (A == null || A.length == 0) {return 0;}int result = A[0];for (int i = 1; i < A.length; i++) {result = result ^ A[i];}return result;}}


0 0
原创粉丝点击