r - 在 R 中计算 4 或 n 和
问题描述
我正在尝试为数据科学家面试练习 LeetCode 问题,R
我遇到的问题之一是foursum。为了解决这个问题,我试图生成所有不同的四种组合并使用apply
函数计算总和。有没有更好的方法来优化它R
而不使用combn
?
GetFourSumCombinations <- function(TestVector,Target){
CombinationPairs = combn(TestVector, 4) ## Get all the combinations
SumOfAllCombinations = apply(CombinationPairs, 2, sum)
TargetElements = which(SumOfAllCombinations == Target)
return(CombinationPairs[,TargetElements])
}
## OutPut:
TestVector = c(1, 0, -1, 0, -2, 2), Target = 0
GetFourSumCombinations(TestVector,0)
[,1] [,2] [,3]
[1,] 1 1 0
[2,] 0 -1 0
[3,] -1 -2 -2
[4,] 0 2 2
解决方案
这是一个较短的版本
GetFourSumCombinations <- function(TestVector,Target){
vals <- combn(TestVector, 4)
vals[, colSums(vals) == Target]
}
GetFourSumCombinations(TestVector, Target)
# [,1] [,2] [,3]
#[1,] 1 1 0
#[2,] 0 -1 0
#[3,] -1 -2 -2
#[4,] 0 2 2
数据
TestVector <- c(1, 0, -1, 0, -2, 2)
Target = 0
推荐阅读
- python - 可调用实例参数的表示法是什么?
- javascript - 如何在 Javascript 中监听控制台命令
- usb - 将输出发送到设备以更改罗技鼠标/键盘中的通道
- css - 有什么办法可以插入类型-??? 不会导致 LBrace 错误???(CSS) 我尝试使用的代码在这里:
- python - 如何在 discord.py 中获取权限对象的所有权限 ID
- postgresql - 使用 copy_from 在大型数据集中复制,使用临时表执行 ON CONFLICT,CardinalityViolation?
- apache-spark - Spark的最后几个任务挂起并且进展非常缓慢
- c - 按下修饰键时获取修改后的键码(字符)
- typescript - 使用扩展语法应用更新时如何处理空/未定义属性?
- webpack - 为什么迁移到 Webpack 5 后 Karma 测试会失败?