Problem · Array
Count Distinct Values in a Huge Sorted Array
Learn this problemProblem statement
Given a non-empty integer array nums sorted in nondecreasing order, return the number of distinct values.
The array may be much larger than the number of distinct values. Use binary search to jump from the first occurrence of one value to the first greater value instead of inspecting every duplicate.
Function
countDistinct(nums: int[]) → intExamples
Example 1
nums = [1,1,1,2,2,4,4,4]return = 3The distinct values are 1, 2, and 4.
Example 2
nums = [-2,-2,-1,0,0,7]return = 4The array contains four distinct values: -2, -1, 0, and 7.
Constraints
numsis non-empty and sorted in nondecreasing order.- Every value is a signed integer.