代码改变世界

268_Missing Number

2016-01-03 10:29  FTD_W  阅读(270)  评论(0编辑  收藏  举报

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的,中间少了一个数字。单独是{0}时候少的是1,单独是{1}时候少的是0

 

用一个数组记录下来0~N出现与否,该数组下标 i 表示数字 i 是否出现,出现过为1。

public class Solution {
    public int MissingNumber(int[] nums) {
        int missingNumber = -1;
        int[] count = new int[nums.Count() + 1];
        for(int i = 0; i < nums.Count(); i++)
        {
            count[nums[i]] = 1;
        }
        for(int i = 0; i < nums.Count() + 1; i++)
        {
            if(count[i] != 1)
            {
                missingNumber = i;
                break;
            }
        }
        return missingNumber;
    }
}