Created
February 15, 2025 18:07
-
-
Save yjunechoe/b949b6b053495301cc11cd90ab3f0b02 to your computer and use it in GitHub Desktop.
Leetcode twosum problem in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
twosum <- function(nums, target) { | |
cur_i <- 1 | |
nxt_i <- cur_i + 1 | |
while(cur_i != length(nums)) { | |
thesum <- nums[cur_i] + nums[cur_i + 1] | |
if (thesum == target) { | |
return(c(cur_i, nxt_i)) | |
} | |
if (nxt_i == length(nums)) { | |
cur_i <- cur_i + 1 | |
nxt_i <- cur_i + 1 | |
} else { | |
nxt_i <- nxt_i + 1 | |
} | |
} | |
return(NULL) | |
} | |
# Tests | |
library(testthat) | |
expect_identical( | |
twosum(c(2, 7, 11, 15), 9), | |
c(1, 2) | |
) | |
expect_identical( | |
twosum(c(3, 2, 4), 6), | |
c(2, 3) | |
) | |
expect_identical( | |
twosum(c(3, 3), 6), | |
c(1, 2) | |
) |
Longest common prefix:
longestcommonprefix <- function(strs) {
shortest <- strs[which.min(nchar(strs))]
cur <- 0
while (cur < nchar(shortest)) {
next_prefix <- substr(shortest, 1, cur + 1)
prefix_is_shared <- all(
sapply(strs, \(str) substr(str, 1, cur + 1) == next_prefix)
)
if (!prefix_is_shared) {
break
}
cur <- cur + 1
}
shared_prefix <- substr(shortest, 1, cur)
shared_prefix
}
# Tests
library(testthat)
expect_identical(
longestcommonprefix(c("flower","flow","flight")),
"fl"
)
expect_identical(
longestcommonprefix(c("dog","racecar","car")),
""
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Last stone weight