zoukankan      html  css  js  c++  java
  • 268. Missing Number

    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

    For example,
    Given nums = [0, 1, 3] return 2.

    Note:
    Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

    本题开始想到的做法是,做一个比nums长+1大的数组,然后把nums里面的每个数组的值赋值到num的序号上面,再一次检测num里面哪个数组值哪个为0;

    public class Solution {

        public int missingNumber(int[] nums) {

           int[] num = new int[nums.length+1];

           for(int i=0;i<nums.length;i++){

               num[nums[i]]++;

           }

           int res = -1;

           for(int i=0;i<num.length;i++){

               if(num[i]==0) res = i;

           }

           return res;

        }

    }

     

    本题看了discussion后发现可以使用位操作,因为本题的隐含条件是序列号,可以把它放在同一的集合里面,当然还包括数组长度,然后观察发现,除了有一个数是单独出现的,其余的都是成对存在,这种题目可以使用异或来做,因为0算是一个特殊的异或,本身和任何数异或都是其他数,所以可以给初值赋值成0,代码如下:

    public class Solution {

        public int missingNumber(int[] nums) {

            int xor = 0;

            for(int i=0;i<nums.length;i++){

                xor = xor^i^nums[i];

            }

            return xor^nums.length;

        }

    }

  • 相关阅读:
    android学习计划2
    在ubuntu12.04下编译android4.1.2添加JNI层出现问题
    android原生系统裁剪
    LM393,LM741可以用作电压跟随器吗?
    android-86-Can't create handler inside thread that has not called Looper.prepare()
    三星 PMU NXE2000,x-powers的AXP228,NXE2000
    当函数没有return时错误
    Perl OOP
    ORA-01031: 权限不足
    Oracle 10g 10.2.0.1 在Oracle Linux 5.4 32Bit RAC安装手冊(一抹曦阳)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6377703.html
Copyright © 2011-2022 走看看