Medium 268题 Missing Number

来源:互联网 发布:java高级程序员 编辑:程序博客网 时间:2024/05/26 19:14
Question:

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?


Solution: I have line of thinking almost immediately~just like the code below!

public class Solution {    public int missingNumber(int[] nums) {        int len=nums.length;        int sum=(0+nums.length+1)*nums.length/2;//The SUM of the all number should be         int res_sum=0;        for(int i=0;i<=nums.length-1;i++)            res_sum+=nums[i];        return sum-res_sum;            }}


0 0