Single Number III——LeetCode

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

 

题目大意:一个数组,有两个元素出现了一次,其余元素都出现两次,让用线性时间复杂度和常量空间复杂度找出这两个数。

解题思路:考虑位操作,对所有元素做异或操作,那么最后得到的值就是要求的两个元素异或得到的,那么找出其中为1的某一位,说明这一位两个数一个为0,一个为1,以这一位为标准,把数组的元素分为两组A、B,那么要求的两个元素肯定是一个在A组,一个在B组,而对这两组各自做异或操作,就可以得到两个数就是要求的。

public class SingleNumberIII {

    public static void main(String[] args) {
        int[] res = singleNumber(new int[]{1, 2, 1, 3, 5, 2});
        System.out.println(Arrays.toString(res));
    }

    public static int[] singleNumber(int[] nums) {
        int[] res = new int[2];
        if (nums == null || nums.length == 0) {
            return res;
        }
        for (int i = 0; i < nums.length; i++) {
            res[0] ^= nums[i];
        }
        int pos = 0;
        for (int i = 0; i < 32; i++) {
            int offset = 1 << i;
            if ((res[0] & (offset)) == offset) {
                pos = i;
                break;
            }
        }
        res[0] = 0;
        int mask = 1 << pos;
        for (int i = 0; i < nums.length; i++) {
            if ((mask & nums[i]) == mask) {
                res[0] ^= nums[i];
            } else {
                res[1] ^= nums[i];
            }
        }
        return res;
    }
}

 

posted @ 2015-08-18 23:45  丶Blank  阅读(1417)  评论(0编辑  收藏  举报