題:
撰寫一個函式,該函式接受一個字串并以整數形式回傳輸入中第二高的數字。
應適用以下規則:
沒有數字的輸入應該回傳 -1 只有一個數字的輸入應該回傳 -1 應該忽略非數字字符 每個數字輸入都應該單獨處理,這意味著如果出現聯合的最高數字,那么第二高的數字也將是最高位 例如:
"abc:1231234" returns 3
"123123" returns 3
【執行時間限制】5秒(r)
[輸入] 字串輸入
輸入字串
[輸出] 整數
第二高的數字
我可以使用 strsplit 和 as.numeric 將字串轉換為數字向量,并去掉 NA(字母)。但不知道從這里去哪里。
澄清:理想的基礎 R 溶液。
到目前為止,我已經得到了這段代碼,雖然很混亂,但它處理了除了聯合最高數字之外的所有情況:
solution <- function(input) {
d <- as.integer(strsplit(input,"")[[1]])
if (any(is.na(d))) {
d <- d[-which(is.na(d))]
}
if(all(is.na(d))) {
return(-1)
}
if (length(is.na(d)) == length(d)-1) {
return(-1)
}
sort(d,TRUE)[2]
}
uj5u.com熱心網友回復:
一個stringr::str_count解決方案:
library(stringr)
secondHighest1 <- function(str) {
ans <- 10L - match(TRUE, cumsum(str_count(str, paste0(9:0))) > 1L)
if (is.na(ans)) -1L else ans
}
一個基本的 R 解決方案:
secondHighest2 <- function(str) {
suppressWarnings(ans <- 10L - match(TRUE, cumsum(tabulate(10L - as.integer(strsplit(str, "")[[1]]))) > 1L))
if (is.na(ans)) -1L else ans
}
更新:借用 Adam 的使用utf8ToInt代替的想法可以strsplit大大提高速度:
secondHighest3 <- function(str) {
nums <- utf8ToInt(str)
nums <- nums[nums < 58L]
if (length(nums) > 1L) max(-1L, max(nums[-which.max(nums)]) - 48L) else -1L
}
set.seed(94)
chrs <- c(paste0(9:0), letters, LETTERS)
str <- paste0(sample(chrs, 1e5, TRUE, (1:62)^4), collapse = "")
secondHighest1(str)
#> [1] 3
secondHighest2(str)
#> [1] 3
secondHighest3(str)
#> [1] 3
microbenchmark::microbenchmark(secondHighest1(str),
secondHighest2(str),
secondHighest3(str))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> secondHighest1(str) 1193.8 1279.55 1524.712 1338.80 1525.2 5013.7 100
#> secondHighest2(str) 16825.3 18049.65 21297.962 19339.75 24126.4 36652.6 100
#> secondHighest3(str) 706.0 774.80 1371.196 867.40 1045.0 17780.4 100
uj5u.com熱心網友回復:
作為單行
string <- "abc:1231234"
sort(unique(suppressWarnings(as.integer(strsplit(string, "", fixed = TRUE)[[1]]))), decreasing = TRUE)[2]
#> [1] 3
或使用magrittr管道:
library(magrittr)
suppressWarnings(
strsplit(string, "", fixed = TRUE)[[1]] %>%
as.integer() %>%
unique() %>%
sort(decreasing = TRUE) %>%
.[2]
)
#> [1] 3
由reprex 包于 2022-03-25 創建(v2.0.1)
uj5u.com熱心網友回復:
您也可以執行類似的操作來轉換為 ASCII 整數。
solution <- function(input) {
if (nchar(input) < 2L) return(-1L)
# ASCII codes for 0:9 are 48:57
int_input <- utf8ToInt(input) - 48L
sort(replace(int_input, !(int_input %in% 0L:9L), -1L), decreasing = TRUE)[2]
}
測驗幾個字串...
str1 <- "abc:1231234"
str2 <- "987654321"
str3 <- "abcdefg4"
str4 <- "abc$<>$#%fgdgLJJ"
str5 <- "123123"
solution(str1)
# [1] 3
solution(str2)
# [1] 8
solution(str3)
# [1] -1
solution(str4)
# [1] -1
solution(str5
# [1] 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454059.html
