260. Single Number III

来源:互联网 发布:三年自然灾害真相知乎 编辑:程序博客网 时间:2024/04/24 15:40

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?

Solution 1 HashMap count the apperance of every number and pick out the number of appearance that does not equal 2

Solution 2 Bit manipulation

//https://leetcode.com/discuss/52351/accepted-java-space-easy-solution-with-detail-explanationspublic static int[] singleNumber(int[] nums) {        // Pass 1 :         // Get the XOR of the two numbers we need to find        int diff = 0;        for (int num : nums) {            diff ^= num;        }        // Get its last set bit        diff &= -diff;        // Pass 2 :        int[] rets = {0, 0}; // this array stores the two numbers we will return        for (int num : nums)        {            if ((num & diff) == 0) // the bit is not set            {                rets[0] ^= num;            }            else // the bit is set            {                rets[1] ^= num;            }        }        return rets;    }


0 0