From 8f18df7d8892dd8b8c15dbc7369fde611babb93f Mon Sep 17 00:00:00 2001 From: William Perron Date: Tue, 28 Feb 2023 14:56:28 -0500 Subject: [PATCH] improve on repeated groups implementation --- repeated-groups/src/main.rs | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/repeated-groups/src/main.rs b/repeated-groups/src/main.rs index eb662e3..2c50ad5 100644 --- a/repeated-groups/src/main.rs +++ b/repeated-groups/src/main.rs @@ -16,32 +16,20 @@ fn main() { fn repeated_groups(nums: Vec) -> Vec> { let mut i = 0; - let mut j = 0; + let mut j = i + 1; let mut res: Vec> = vec![]; - let mut curr: Vec = vec![]; - while j < nums.len() { - if nums[i] != nums[j] { - if curr.len() > 1 { - res.push(curr); - } - - i = j; + while j < nums.len() && nums[i] == nums[j] { j += 1; - curr = vec![nums[i]]; - continue; } - curr.push(nums[i]); - j += 1; - } + if j - i > 1 { + res.push(nums[i..j].to_vec()); + } - // If the last iteration is a repeated group, the loop exits before appending - // the last group to the results, so we check here for what the last group was - // and add it to the result if need be. - if curr.len() > 1 { - res.push(curr); + i = j; + j += 1; } res