LeetCode-Missing Number

来源:互联网 发布:旅行商问题背包算法 编辑:程序博客网 时间:2024/05/29 02:45

题目:

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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

一、二分法

思路:先将数组排好序,当中点数  mid  等于对应下标数  nums[mid]  时,说明缺失数在中点数的右边,再将区间起点设置为 [mid + 1,nums.length - 1],如果不相等则说明缺失数在中点数的左边,设置查找区间为  [ min,mid - 1 ];如果是最后一位缺失,则整个数组没有错位,返回最后一位加1。

代码如下(Java):


    

二、等差数列查找法

思路:大小为n的数组里的所有数都是0 - n之间的数,作为等差数列,如果没有缺失的时候它的和是能O(1)计算出来的,所以我们遍历一遍记录最大、最小和数组和,用期望数组和减去实际数组和,就是缺失的整数;缺失0和缺失n的时候要特殊处理,因为他们俩的期望和减去实际和都是0。记录最小值可以用来判断是否缺失0。


代码:



0 0
原创粉丝点击