我正在尝试在if语句中返回一个数组,但是什么也没有返回。当我console.log([i,j])时,它工作正常。
const twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [ i, j ];
}
}
}
};
twoSum([ 2, 7, 11, 15 ], 9);
我知道这不是解决此问题的最有效方法,但我只是在学习基础知识,因此为什么不返回任何内容我感到非常困惑。
答案 0 :(得分:0)
它应该返回# Todo lo haremos con base en un variable aleatoria Uniforme(0,1).
set.seed(26) ; n = 10000
U<-runif(n = n)
# Supongamos que queremos simular de una exponencial.
# Función de distribución: F(X) = 1-exp(-lambda*X) = U
# Entonces, X = F^(-1)(X)= log(1-U)/(-lambda)
lambda = 1/6 # El parámetro de la exponencial que vamos a usar.
X <- log(1-U)/(-lambda)
library(ggplot2)
p <- qplot(X,
geom="histogram",
binwidth = 2,
boundary = 0, #This controls the bin alignment with the y-axis
main = "Histograma de X",
xlab = "Observaciones",
# La función "I" hace que no aparezca una descripción.
fill=I("yellow"),
col=I("blue"),
alpha=I(0.2),
xlim=c(0,50))+
geom_hline(yintercept = 0,col="red",lwd=1)+
geom_vline(xintercept = 0,col="red",lwd=1)
# geom_histogram(binwidth = 1, boundary = 0, closed = "left")
p
。
如果要在控制台中显示结果,请尝试:
[0, 1]
答案 1 :(得分:0)
也许您可以用这种方式编写它,以便于阅读。有两个for循环很难处理。如果我们知道数组只有正数,就可以对其进行优化。
const twoSum = (nums, target) => {
let found = null;
nums.some((n, i) => {
// here you figure where you are looking for.
const lookingFor = target - n;
const idx = nums.indexOf(lookingFor, i);
if (idx !== -1) {
found = [i, idx];
return true;
}
return false;
});
return found;
};
console.log(twoSum([ 2, 7, 11, 15 ], 9));