[LeetCode] Number of Equal Numbers Blocks

2936. Number of Equal Numbers Blocks

You are given a 0-indexed array of integers, nums. The following property holds for nums:

  • All occurrences of a value are adjacent. In other words, if there are two indices i < j such that nums[i] == nums[j], then for every index k that i < k < j, nums[k] == nums[i].

Since nums is a very large array, you are given an instance of the class BigArray which has the following functions:

  • int at(long long index): Returns the value of nums[i].
  • void size(): Returns nums.length.

Let’s partition the array into maximal blocks such that each block contains equal values. Return the number of these blocks.

Note that if you want to test your solution using a custom test, behavior for tests with nums.length > 10 is undefined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for BigArray.
* class BigArray {
* public:
* BigArray(vector<int> elements);
* int at(long long index);
* long long size();
* };
*/
class Solution {
public:
int countBlocks(BigArray* nums) {
long long res = 0, n = nums->size(), lst = nums->at(n-1);
for(long long i = 0, j = 0; i < n; i = j + 1) {
long long skip = 1, val = nums->at(i);
if(lst == val) {
return res + 1;
}
while(1) {
if(nums->at(min(j+skip,n-1)) != val) {
if(skip == 1) break;
skip = 1;
} else j += skip, skip *= 2;
}
res += 1;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/13/PS/LeetCode/number-of-equal-numbers-blocks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.