zoukankan      html  css  js  c++  java
  • 0-n-1中缺失的数字-算法总结笔记

    算法题目

    0-n-1中缺失的数字

    一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。
    在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。

    示例 1:

    输入: [0,1,3]
    输出: 2
    

    示例 2:

    输入: [0,1,2,3,4,5,6,7,9]
    输出: 8
    

    限制:
    1 <= 数组长度 <= 10000

    测试用例

    [1] [0,1,3] [0,1,2] [1,2,3] [0,1,2,3,4,5,6,7,9]
    

    思路分析

    解法一:直接遍历

    思路:由于数组的递增有序,并且求出缺失的数字,那么直接判断当前数字是否等于前面一个数字+1,
    ​ 否则就返回缺失数字
    分析:时间复杂度为O(n),空间复杂度为O(1)
    思考:缺失的数字主要在数组头部,中间,尾部,注意这三个位置来编写代码。

    解法二:二分法

    思路:由于数组是排好序的,可以使用二分法,比较中间元素和序号是否相同,然后改变查找空间继续
    ​ 判断。
    分析:时间复杂度为O(logn),空间复杂度为O(1)

    /**
    
    @author cosefy
    
    @date 2020/6/25
    */
    public class MissingNumber {
    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 3, 5};
        int res1 = test1(nums);
        System.out.println("解法一的结果是: " + res1);
        int res2 = test2(nums);
        System.out.println("解法二的结果是: " + res2);
    }
    
    //解法一:直接遍历
    public static int test1(int[] nums) {
        int prenum = -1;
        for (int num : nums) {
            if (num != ++prenum) {
                return prenum;
            }
        }
        return prenum + 1;   //当数组元素缺失在尾部时,返回prenum+1
    }
    
    //解法二:二分法
    public static int test2(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (right + left) / 2;
            if (mid == nums[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
    }
    
  • 相关阅读:
    net 5 小常识试图及时编译
    C# CLR核心机制
    grpc 错误记录一下 掉坑里爬了三天
    基于docker 做的 kafka 集群 3分区
    efcore 查用命令
    vps检测
    IntelliJ Idea 2017 免费激活方法
    jQuery设置disabled属性与移除disabled属性
    Myeclipse中js文件中的乱码处理
    关于html中frameset下frame之间的交互,以及html中iframe和原html之间的交互
  • 原文地址:https://www.cnblogs.com/cosefy/p/13192580.html
Copyright © 2011-2022 走看看