博客说明java
文章所涉及的资料来自互联网整理和我的总结,意在于我的学习和经验汇总,若有什么地方侵权,请联系本人删除,谢谢!数组
剑指offer,53-II学习
0~n-1中缺失的数字code
一个长度为n-1的递增排序数组中的全部数字都是惟一的,而且每一个数字都在范围0~n-1以内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。排序
示例 1:leetcode
输入: [0,1,3] 输出: 2
示例 2:get
输入: [0,1,2,3,4,5,6,7,9] 输出: 8
判断下标是否为当前的数,不是直接返回博客
class Solution { public int missingNumber(int[] nums) { for(int i = 0;i<nums.length;i++){ if(nums[i] != i){ return i; } } return nums.length; } }
使用二分法io
class Solution { public int missingNumber(int[] nums) { int i = 0; int j = nums.length - 1; while(i <= j){ int m = (i+j)/2; if(nums[m] == m){ i = m + 1; }else{ j = m - 1; } } return i; } }
感谢class
leetcode
以及勤劳的本身 关注公众号: 归子莫,获取更多的资料,还有更长的学习计划