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?
题意 :给出一个由0到n之间整数组成的数组,数组个数为n,每个元素不相等,问数组中缺少哪个数,要求时间复杂度为O(n),空间复杂度为O(1)
思路:用置换的方法,在每次循环时,获取当前下标的数组元素,在将tmp赋值给nums[tmp]前,将nums[tmp]放在临时变量中,如果循环操作,下去越界或者与起始位置重合
代码如下
class Solution { public int missingNumber(int[] nums) { for (int i = 0; i < nums.length; i++) { int tmp = nums[i]; nums[i] = -1; while (tmp != -1 && tmp < nums.length) { int t = nums[tmp]; nums[tmp] = tmp; tmp = t; } } int res = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] != i) { res = i; break; } } if (res == -1) res = nums.length; return res; } }