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;

        }

    }

  • 相关阅读:
    第 16 章 CSS 盒模型[下]
    第 16 章 CSS 盒模型[上]
    第 15 章 CSS 文本样式[下]
    第 15 章 CSS 文本样式[上]
    第 14 章 CSS 颜色与度量单位
    第 13 章 CSS 选择器[上]
    第 12 章 CSS 入门
    关于springboot上传文件报错:The temporary upload location ***is not valid
    Java Enum枚举 遍历判断 四种方式(包括 Lambda 表达式过滤)
    git命令-切换分支
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6377703.html
Copyright © 2011-2022 走看看