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:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-05  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 17801
  • 日志数: 12
  • 建立时间: 2014-05-21
  • 更新时间: 2014-06-03

RSS订阅

Open Toolbar