您的位置:首页 > 其它

【LeetCode】268. Missing Number

2016-02-25 22:48 393 查看
源地址

题目

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?

public class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = ((1 + n) * n )/ 2;
int sum1 = 0;
for(int i = 0 ; i < n ;i++)
{
sum1 += nums[i];
}
int ans = sum - sum1;
return ans;
}
}


思路

n项和公式 sum = (n + 1) * n / 2

遍历数组,所有数相加和 减去sum就是missing的数

O(n)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode