js 数组算法题收集

找出某段连续数组的缺失值

// The output of the function should be 8
var array_of_integers = [2, 5, 1, 4, 9, 6, 3, 7];
var upper_bound = 9;//可用MATH.MAX或者MATH.MIN找出最大和最小值
var lower_bound = 1;
 
findMissingNumber(array_of_integers, upper_bound, lower_bound); //8
 
function findMissingNumber(array_of_integers, upper_bound, lower_bound) {
 
  // Iterate through array to find the sum of the numbers
  var sum_of_integers = 0;
  for (var i = 0; i < array_of_integers.length; i++) {
    sum_of_integers += array_of_integers[i];
  }
  //先找出该段连续数组的实际总和
// 以高斯求和公式计算理论上的数组和 // Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2]; // N is the upper bound and M is the lower bound upper_limit_sum = (upper_bound * (upper_bound + 1)) / 2; lower_limit_sum = (lower_bound * (lower_bound - 1)) / 2; theoretical_sum = upper_limit_sum - lower_limit_sum;//理论上完整连续数组的求和公式 // return (theoretical_sum - sum_of_integers) //理论-实际的总和差值即为该连续数组的缺失元素 }

总结思路:

原文地址:https://www.cnblogs.com/slb1994/p/6623091.html