LeetCode # Array # Easy # 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.

题目:给一个无序数组,长度为n,元素为从0到n,缺少一个,求缺了哪一个?

思路:/*自己的思路太差了,然后看了最佳解法,人比人气死人啊*/ 

   最佳解法:从0到n的累加和是一定的,求出现有数组的sum,然后两个相减就是缺少的元素。

1 class Solution {
2     public int missingNumber(int[] nums) {
3         int sum = (nums.length + 1) * nums.length / 2, add = 0;//求和1
4         for(int i : nums) add += i;//求和2
5         return (sum - add);
6     }
7 }

猜你喜欢

转载自www.cnblogs.com/DongPingAn/p/9016646.html