Leetcode OJ平台上的SingleNumber题目用Java实现
上一篇 /
下一篇 2014-06-03 09:27:37
/ 个人分类:学习
原题如下:
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,异或满足交换律,即a^b^c = a^c^b,所以只要将数组从头至尾异或一遍,结果就是只出现过一次的数字。谢谢木易先森的指导。
源代码如下:
public class Solution {
public static int singleNumber(int[] A) {
int result = 0 ;
for(int i = 0; i < A.length; ++ i){
result = result ^ A[i];
}
return result;
}
public static void main(String agrs[]){
int[] A = {1,1,2,3,4,5,2,3,5};
int result = singleNumber(A);
System.out.println(result);
}
}
收藏
举报
TAG: