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?
这道题看起来挺简单的,但是有个陷阱就是他的array不是sorted的,要么自己sort(但是至少O(nlongn),所以用其他办法。除了我这个办法其实还有个数学的方法,把所有数字加起来,然后减掉,N个连续数想加的结果。
public class Solution { public int missingNumber(int[] nums) { int[] n = new int[nums.length+1]; for(int i=0;i<nums.length;i++){ n[nums[i]] ++; } for(int i=0;i<n.length;i++){ if(n[i]!=1){ return i; } } return nums.length; } }