-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
求 最接近的值 #109
Comments
const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37;
function getClose(num, arr){
let res = arr[0];
for(let i = 1; i < arr.length; i++){
if(Math.abs(arr[i] - num) < Math.abs(res - num)){
res = arr[i];
}
}
return res;
}
const res = getClose(num, arr);
console.log(res); |
function getClose(target, arr) {
let cloest = [Number.MAX_SAFE_INTEGER, 0];
arr.forEach((element) => {
let temp = Math.abs(element - target);
if (temp < cloest[0]) {
cloest[0] = temp;
cloest[1] = element;
}
});
return cloest[1];
}
console.log(getClose(num, arr)); |
function main(arr, num){
const dif = arr.map(item => Math.abs(item - num));
let minIndex = 0;
for(let i = 1; i < arr.length; ++i){
dif[i] < dif[minIndex] && (minIndex = i);
}
return arr[minIndex];
} |
function getClose(target, arr) {
const dif = arr.map(item => Math.abs(item - target));
const min = Math.min(...dif);
const index = dif.findIndex(i => i === min);
return arr[index];
} |
function findClosest(arr,num){
var closestArr = arr.map(function(val){
return Math.abs(num-val);
});
var minDiff = Math.min(...closestArr);
var indexArr=[];
closestArr.forEach(function(val,i){
if(val === minDiff)
indexArr.push(i);
});
if(indexArr.length >1)
return indexArr.map(i=>arr[i]);
else
return arr[closestArr.indexOf(minDiff)];
}
let arr1= [3 ,56 ,56 ,23 ,7 ,76 ,-2 ,345 ,45 ,76];
let num1=37;
console.log(findClosest(arr1,num1)); // 输出:45
let arr2=[1, 2, 3];
let num2=2;
console.log(findClosest(arr2,num2)); // 输出:2
let arr3=[1, 3];
let num3=2;
console.log(findClosest(arr3,num3)); // 输出: [1, 3] |
function a(arr, num) { |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: