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).
1import java.util.ArrayList;
2import java.util.List;
3
4public class Main {
5 public static List<Integer> findConsecutiveNumbers(int[] nums) {
6 List<Integer> result = new ArrayList<>();
7 int count = 1;
8 for (int i = 1; i < nums.length; i++) {
9 if (nums[i] == nums[i - 1]) {
10 count++;
11 if (count == 3 && !result.contains(nums[i])) {
12 result.add(nums[i]);
13 }
14 } else {
15 count = 1;
16 }
17 }
18 return result;
19 }
20
21 public static void main(String[] args) {
22 int[] nums = {1, 1, 1, 2, 1, 2, 2};
23 System.out.println(findConsecutiveNumbers(nums));
24 }
25}
26
In Java, we use an ArrayList to record any number that appears at least three consecutive times in the array. This list is returned and printed.
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.
1#
In C, we use an auxiliary array to mimic a hashmap for counting occurrences of numbers. We focus on consecutive occurrences rather than entire counts, thus determining which numbers are consecutive.