您的位置:首页 > 其它

[leetcode]Missing Number

2016-01-30 10:21 281 查看
题目描述如下:

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.

想到的解决方法是假设数字是齐全的,利用等差公式计算应有和,减去现有的数字和即可。代码如下:

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


题目链接:https://leetcode.com/problems/missing-number/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: