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?

原问题链接:https://leetcode.com/problems/single-number/

问题分析

  这个问题的解决思路相对来说就比较简单了。只是用到了一个小的技巧。如果能想到的话就没什么了。在问题描述中说到,数组中所有元素都出现两次,除了一个元素。而这里就是要找这个独特的元素。那么有没有什么办法找到这个元素呢?

  一种理想的情况就是我通过一次遍历,能够使得所有重复出现的元素都被消去了,只留下这个独特的元素。这个时候,如果我们借用一个位运算的小技巧,比如异或运算,那么就可以得到这个结果了。因为对于两个相同的元素来说,它们的异或运算结果就是0。所以我们对里面所有的元素按照这个方式遍历一遍,就可以得到最终的结果。

  详细的代码实现如下:

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

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2309164