Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Question: Given an unordered array of length n and elements from 0 to n, if one is missing, which one is missing?
Ideas: /*My own ideas are too bad, and then I read the best solution, people are more popular than dead people*/
The best solution: the cumulative sum from 0 to n is certain, find the sum of the existing array, and then subtract the two to get the missing element.
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 }