Sponsored
We can use a sliding window approach with a counter to track consecutive numbers as we iterate through the list.
Time Complexity: O(n), where n is the number of elements in the list. Space Complexity: O(1).
1#include <iostream>
2#include <vector>
3using namespace std;
4
5vector<int> findConsecutiveNumbers(vector<int> nums) {
6 vector<int> result;
7 int count = 1;
8 for (size_t i = 1; i < nums.size(); i++) {
9 if (nums[i] == nums[i - 1]) {
10 count++;
11 if (count == 3) result.push_back(nums[i]);
12 } else {
13 count = 1;
14 }
15 }
16 return result;
17}
18
19int main() {
20 vector<int> nums = {1, 1, 1, 2, 1, 2, 2};
21 vector<int> result = findConsecutiveNumbers(nums);
22 for (int num : result) cout << num << endl;
23 return 0;
24}
25
In C++, we use a vector to store our numbers and a similar counter logic to the C solution. Once three consecutive numbers are found, they are added to the result vector.
This approach uses a HashMap (or Dictionary in Python) to keep track of the sequence counts of numbers. This way, we can determine if any number is repeated consecutively at least three times.
Time Complexity: O(n). Space Complexity: O(1) since we use only limited extra space.
1function
In JavaScript, an object serves the function of a dictionary to prevent redundant consecutive recordings, thereby refining output efficiency when consecutive numbers are detected.