LeetCode -- Missing Number
題目描述:
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?
在一個從[0,n]區間的序列中找到拿掉的那一個數。
思路:
使用長度+1的bool數組做標記,找到沒有被標記的那個即可。
實現代碼:
public class Solution {
public int MissingNumber(int[] nums) {
var flag = new bool[nums.Length + 1];
for(var i =0 ;i < nums.Length; i++){
flag[nums[i]] = true;
}
for(var i = 0;i < flag.Length; i++){
if(!flag[i]){
return i;
}
}
return -1;
}
}