LeetCode-in-Java

4038. Count Integers Appearing in a Single Block

Easy

You are given an integer array nums.

An integer x is special if all occurrences of x in nums appear in a single contiguous block.

Return the number of distinct special integers in nums.

Example 1:

Input: nums = [1,2,2,1]

Output: 1

Explanation:

Therefore, there is one special integer.

Example 2:

Input: nums = [3,3,1,2,2,1]

Output: 2

Explanation:

Therefore, there are two special integers.

Constraints:

Solution

public class Solution {
    public int countSpecialIntegers(int[] nums) {
        boolean[] seen = new boolean[101];
        boolean[] special = new boolean[101];
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i == 0 || nums[i] != nums[i - 1]) {
                if (seen[nums[i]]) {
                    special[nums[i]] = false;
                } else {
                    seen[nums[i]] = true;
                    special[nums[i]] = true;
                }
            }
        }
        for (int x = 1; x <= 100; x++) {
            if (special[x]) {
                count++;
            }
        }
        return count;
    }
}