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:
[5, 3] is also correct.解调思路:考察位运算。题目描述说数组中除了有两个数只出现了1次之外其余的书都出现了两次。因此可以相等使用异或的方法。但是将数组所有的元素都进行异或得到的结果是两个只出现1次的数异或后的结果,如何能得到那两个只出现了1次的数呢?通过观察我们可以发现异或的结果的二进制表示有0有1,这表明这两个数是有差异的。我们可以从异或结果的二进制表示中找到从低位往高位数第一个为1的位置,根据异或的性质可知这个位置正好可以区分这两个数。因此我们可以根据这一位是否为1,将数组分为两部分。这样问题就变成了求single number 的问题了。
1 public class Solution { 2 public int[] singleNumber(int[] nums) { 3 int xorResult = 0; 4 int[] result = new int[2]; 5 for (int i = 0; i < nums.length; i++) { 6 xorResult ^= nums[i]; 7 } 8 int ident = xorResult & -xorResult; 9 for (int i = 0; i < nums.length; i++) { 10 if ((nums[i] & ident) != 0) { 11 result[0] ^= nums[i]; 12 } 13 } 14 result[1] = result[0] ^ xorResult; 15 return result; 16 } 17 }
原文:http://www.cnblogs.com/FLAGyuri/p/5746314.html