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

  • 相关阅读:
    matlab 工具箱下载地址
    P3022 [USACO11OPEN]Odd degrees G
    P1052 过河 【dp】
    P1156 垃圾陷阱
    P1063 能量项链 【区间dp】
    P1026 统计单词个数 【dp】
    P1541 乌龟棋【记忆化搜索】
    P1736 创意吃鱼法 【dp】
    单调队列优化多重背包 洛谷P1776 宝物筛选
    单调队列 洛谷P1886 滑动窗口
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/5364888.html
Copyright © 2011-2022 走看看