Given an array of integers, count how many distinct values exist in the array.
Example:
Input: [1, 5, -3, 1, -4, 2, -4, 7, 7] Output: 6 Explanation: the distinct values in the array are [1, 5, -3, -4, 2, 7]
Note:
For this lesson, your algorithm should run in O(n log n) time and use O(1) extra space.
(There are faster solutions which we will discuss in future lessons)
Hints:
Let's sort the array in non-decreasing order. In this way all the equal elements will come one after another.
Then, we can traverse the sorted array from left to right using an index
i. We should increment the solution if value nums[i] has not been seen before. How can we check this?
nums[i] has never been seen before if nums[i] != nums[i - 1].
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check