首页 > 其他 > 详细

Single Number III

时间:2016-04-07 20:19:51      阅读:189      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!