首页 > 其他 > 详细

LeetCode Single Number III

时间:2015-10-25 08:29:45      阅读:273      评论:0      收藏:0      [点我收藏+]

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

Single NumberSingle Number II类似,也是一道bit manipulation. 

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

通过这个digit把原来的nums 数组分成两类,一类这个digit上是0一类这个digit上是1, 一类xor出一个结果就是最后的res.

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

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 }

 

LeetCode Single Number III

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4908197.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!