给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。
您在真实的面试中是否遇到过这个题?
Yes
样例
N = 4 且序列为 [0, 1, 3] 时,缺失的数为2。
注意
可以改变序列中数的位置。
挑战
在数组上原地完成,使用O(1)的额外空间和O(N)的时间。
标签 Expand
相关题目 Expand
解题思路:
当想到是否可以把数组中的元素放入“合适”的位置时,豁然开朗,例如将1放在0位置上,2放在1位置上。。。,最后变量数组,如果某个位置上的数不合适,则返回该位置上“合适”的数
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
for(int i=0;i<nums.length-1;i++){
while(nums[i]!=i){
int j = nums[i];
if(j==nums.length){
break;
}
swap(i, j, nums);
}
}
for(int i=0;i<nums.length-1;i++){
if(nums[i]!=i){
return i;
}
}
return nums.length;
}
public void swap(int l, int r, int[] A) {
int tmp = A[l];
A[l] = A[r];
A[r] = tmp;
}
}