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

     思路:

    1.先将数组排序,再遍历一遍即可,但是比较慢

    2.(最快的)新建一个数组,数组是原数组长度加一,每个新数组元素初始化为零。遍历原数组,将新数组相应位置的元素设为-1。遍历新数组,找到元素值不为-1的位置,返回该位置索引值。

    public class S268 {
        public int missingNumber(int[] nums) {
            //slow 排序会影响时间
    /*        Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if(i != nums[i])
                    return i;
            }
            return nums[nums.length-1]+1;
            */
            //best
            int []nums2 = new int[nums.length+1];
            for (int i = 0; i < nums.length; i++) {
                nums2[nums[i]] = -1;
            }
            int i = 0;
            for (; i < nums2.length; i++) {
                if (nums2[i] != -1)
                    break;
            }
            return i;
        }
    }
  • 相关阅读:
    留言板
    文件操作1
    JQUERY与JS的区别
    PHP 练习租房
    PHP 投票练习
    PHP,单项查询及多项查询
    PHP 增删改查 import!!
    PHP 数据访问
    PHP 对象及其三大特性
    正则表达式和数组
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5362252.html
Copyright © 2011-2022 走看看