260. Single Number III

来源:互联网 发布:excel表格数据链接 编辑:程序博客网 时间:2024/05/17 07:30

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?

思路:

原本只有一个single number时是2*n+1的格局,现在变成了2*n+2的格局,所以只要想办法把他分解成两个2*n+1就可以了

所有的数字异或之后得到的结果是两个single number的异或xor(例如:3^5 0110),然后这个结果取补码得到-xor(例如:- 3^5 1010)

这两个结果取与得到xor从低位到高位,第一个非0数字的位置(例如lowbit = xor & -xor = 0010 & 0011 = 0010 3和5在二进制中第二位开始不同)

然后根据这个结果lowbit来区分数组中的数,由于异或的属性“同0异1”,所以这两个single number和lowbit的与的结果一定不同


public int[] singleNumber(int[] nums) {int xor = nums[0];int res[] = new int[2];       for (int i = 1; i < nums.length; i++) {xor ^= nums[i];}int lowbit = xor & -xor;res[0] = 0;res[1] = 0;for (int i = 0; i < nums.length; i++) {if ((lowbit & nums[i]) != 0) {res[0] ^= nums[i];} else {res[1] ^= nums[i];}}return res;}


0 0
原创粉丝点击