给定一个乱序而且缺少一个值的连续自然数数组如下面代码的arrayOfIntegers,求再O(n)下找到缺少的值。
说来惭愧,初步思考有点摸不清思路,看了代码后才明白这不就是初中数学题码?
原答案:
// The output of the function should be 8
var arrayOfIntegers = [2, 5, 1, 4, 9, 6, 3, 7];
var upperBound = 9;
var lowerBound = 1;
console.log(findMissingNumber(arrayOfIntegers, upperBound, lowerBound)); // 8
function findMissingNumber(arrayOfIntegers, upperBound, lowerBound) {
// Iterate through array to find the sum of the numbers
var sumOfIntegers = 0;
for (var i = 0; i < arrayOfIntegers.length; i++) {
sumOfIntegers += arrayOfIntegers[i];
}
// Find theoretical sum of the consecutive numbers using a variation of Gauss Sum.
// Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2];
// N is the upper bound and M is the lower bound
upperLimitSum = (upperBound * (upperBound + 1)) / 2;
lowerLimitSum = (lowerBound * (lowerBound - 1)) / 2;
theoreticalSum = upperLimitSum - lowerLimitSum;
return theoreticalSum - sumOfIntegers;
}
但是给了首项和末项,也可以很快用高斯求和。
function missing (arr, up, low) {
// 项数
let long = up - low + 1;
let gaussSum = (low + up) * long / 2;
let len = arr.length;
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return gaussSum - sum;
}
console.log(missing(arrayOfIntegers, upperBound , lowerBound));
给定一个数组,求后面元素减去前面元素的最大差值
var array = [7, 8, 4, 9, 9, 15, 3, 1, 10];
function max(arr) {
let len = arr.length;
let newArr = [];
for (let i = 0; i < len; i++) {
let temp = arr[i];
for (let e = i + 1; e < len; e++) {
if (arr[e] > temp) {
temp = arr[e]
}
newArr.push(temp - arr[i]);
}
}
newArr.sort((a,b) => b - a);
return newArr[0];
}
console.log(max(array))
可以不用newArr,存结果,直接更新最大差值就可以, 我觉得这个更符合我的思维就这样写了。
Given an array of integers, return an output array such that output[i] is equal to the product of all the elements in the array other than itself. (Solve this in O(n) without division)
var firstArray = [2, 2, 4, 1];
var secondArray = [0, 0, 0, 2];
var thirdArray = [-2, -2, -3, 2];
function except(arr) {
let res = [];
let temp = 1;
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let e = 0; e < len; e++) {
if (e != i) {
temp = temp * arr[e];
}
}
res.push(temp);
// 一个循环结束把变量变为1
temp = 1;
}
return res;
}
console.log(except(firstArray));
console.log(except(secondArray));
console.log(except(thirdArray));
找数组的交集,非常简单,但太晚了,我就随便谢谢。
var firstArray = [2, 2, 4, 1];
var secondArray = [1, 2, 0, 2];
function intersection(arr1, arr2) {
let res = [];
let len = arr1.length;
for (let i = 0; i < len; i++) {
if(arr2.includes(arr1[i])) {
res.push(arr1[i]);
}
}
res = [...new Set(res)];
return res;
}
console.log(intersection(firstArray, secondArray));