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?
思路:
1.先将数组排序,再遍历一遍即可,但是比较慢
2.(最快的)新建一个数组,数组是原数组长度加一,每个新数组元素初始化为零。遍历原数组,将新数组相应位置的元素设为-1。遍历新数组,找到元素值不为-1的位置,返回该位置索引值。
public class S268 { public int missingNumber(int[] nums) { //slow 排序会影响时间 /* Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if(i != nums[i]) return i; } return nums[nums.length-1]+1; */ //best int []nums2 = new int[nums.length+1]; for (int i = 0; i < nums.length; i++) { nums2[nums[i]] = -1; } int i = 0; for (; i < nums2.length; i++) { if (nums2[i] != -1) break; } return i; } }