zoukankan      html  css  js  c++  java
  • 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.
    
    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

  • 相关阅读:
    BETA 版冲刺前准备
    alpha事后诸葛亮
    alpha冲刺10
    alpha冲刺9
    alpha冲刺8
    alpha冲刺7
    alpha冲刺6
    alpha冲刺5
    第十一次作业
    Alpha冲刺一 (10/10)
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/5364888.html
Copyright © 2011-2022 走看看