0n1中缺失的数字算法总结笔记

2次阅读

共计 972 个字符,预计需要花费 3 分钟才能阅读完成。

算法题目

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;
}
}
正文完
 0