美文网首页
268. Missing Number

268. Missing Number

作者: Kim_9527 | 来源:发表于2017-04-15 15:56 被阅读7次

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.

Already Pass Solution

    public int MissingNumber(int[] nums) {
        int result = nums.Length * (nums.Length + 1) / 2;
        foreach(int i in nums)
        {
            result -= i;
        }
        return result;
    }

解决思路:
(1)利用遗失这个条件,用没有遗失的状态求出遗失的部分
(2)使用foreach比for会快一些

待思考:
(1)如果丢失的数字为几个该如何解决

相关文章

网友评论

      本文标题:268. Missing Number

      本文链接:https://www.haomeiwen.com/subject/jhonattx.html