LeetCode 260. Single Number III

原题链接在这里:https://leetcode.com/problems/single-number-iii/

题目:

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.

Example:

Input:  [1,2,1,3,2,5]
Output: [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?

题解:

思路是逐个xor, 得到的结果是两个出线单次的数字a 和 b 的异或,axorb. a 与 b 不相同,所以a, b 取 xor肯定不为0,通过axorb $ (-axorb)找到 axorb中从右往左第一个不为0的digit. 

通过这个digit把原来的nums 数组分成两类,一类这个digit上是0一类这个digit上是1. res[0] 来 xor 第一类, res[1] 来 xor 第二类.

Note: 位运算级别很低,需要用() 保护。

Time Complexity: O(nums.length).

Space: O(1).

AC Java:

 1 public class Solution {
 2     public int[] singleNumber(int[] nums) {
 3         int [] res = {0,0};
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         //internal result a XOR b
 8         int axorb = 0;
 9         for(int i = 0; i<nums.length; i++){
10             axorb ^= nums[i];
11         }
12         
13         //from right to left, mark first digit that a and b are different
14         //通过这个mark把 原nums 数组分成两类,一类这个digit上是1,一类这个digit上是0.
15         int mark = axorb & (-axorb);
16         for(int i = 0; i<nums.length; i++){
17             if((nums[i] & mark) != 0){
18                 res[0] ^= nums[i];
19             }else{
20                 res[1] ^= nums[i];
21             }
22         }
23         return res;
24     }
25 }

类似Single NumberSingle Number II.  

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4908197.html