LeetCode 268. Missing Number (缺失的数字)

Posted 几米空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 268. Missing Number (缺失的数字)相关的知识,希望对你有一定的参考价值。

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?

 


 题目标签:Array

  题目给了我们一个nums array, array 里是从0 到n 的所有数字, 但是会缺失一个,让我们找出来,数字的排列不是有序的。

  既然我们知道n,而且数字是从0 到 n 的,可以利用等差数列求和公式 (首项+尾项) * 个数/2 求出总和, 再遍历一次nums 算出实际的sum, 然后差值就是缺失的那个数字了。

 

Java Solution:

Runtime beats 49.88% 

完成日期:04/27/2017

关键词:Array

关键点:等差数列求和公式

 1 class Solution 
 2 {
 3     public int missingNumber(int[] nums) 
 4     {
 5         int cSum = (0 + nums.length) * (nums.length + 1) / 2;
 6         int sum = 0;    
 7         
 8         for(int i=0; i<nums.length; i++)
 9         {
10            sum += nums[i];
11         }
12         
13         return cSum - sum;
14     }
15 }

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

以上是关于LeetCode 268. Missing Number (缺失的数字)的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-268 Missing Number

LeetCode:268. Missing Number

LeetCode OJ 268Missing Number

LeetCode OJ 268Missing Number

leetcode268 - Missing Number - easy

LeetCode 268. Missing Number