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;
       
    }
}


你可能感兴趣的:(LeetCode -- Missing Number)