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;

        }

    }

  • 相关阅读:
    从头学pytorch(十二):模型保存和加载
    Python环境安装与配置
    PyCharm安装及使用
    Python包管理工具pip的基本使用
    LoadRunner安装破解
    正则表达式提取器使用
    TCPMon使用总结
    JMeter:全面的乱码解决方案
    Jmeter脚本两种录制方式
    监听器-【聚合报告】界面字段解析及计算方法概要说明
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6377703.html
Copyright © 2011-2022 走看看