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/

posted @ 2017-09-09 11:39  Jimmy_Cheng  阅读(235)  评论(0编辑  收藏  举报