码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number III

时间:2016-04-07 20:21:20      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

原文:
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:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question
简单的点说,就是一个数组中有两个不一样的数不是成对出现的,其他的数都是成对出现的

 

public int[] singleNumber(int[] nums) {
        int mid = 0, index = 0, left = 0, right = 0;
        //计算数组中所有的数的异或的值,记为mid
        for(int i = 0, len = nums.length;i < len;i ++){
            mid = mid ^ nums[i];
        }

        //查找mid中最低位的1是第几位,记为index
        while((mid & (1 << index)) == 0){
            index ++;
        }
        
                //根据数组中的数第index位是1或0的不同,进行划分为两部分,而这两部分正好有两个不同的数,其余的数都是成对出现的
        for(int i = 0, len = nums.length;i < len;i ++){
            if((nums[i] & (1 << index)) == 0){
                left = left ^ nums[i];
            }else{
                right = right ^ nums[i];
            }
        }
        return new int[]{left, right};
    }

 

参考:

http://blog.csdn.net/morewindows/article/details/8214003

Single Number III

标签:

原文地址:http://www.cnblogs.com/xiaoxian1369/p/5364888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!