X1503: Count Distinct

Problem Description

Write a method countDistinct that takes an array of integers and returns the count of distinct (unique) numbers present in the array.

Method Signature:

public int countDistinct(int[] nums)

Constraints

  • You must use a TreeSet<Integer> as the class to store the set.
  • Store each number in the array, ensuring only unique values are stored.
  • Return the size of the set, which will give the count of distinct numbers.
  • The array will contain at least one integer.
  • The array may contain both positive and negative integers.
  • The TreeSet will automatically handle duplicate values, so you only need to focus on inserting numbers.

Documentation

Examples:

countDistinct({1, 2, 3, 2, 4, 1}) -> 4
countDistinct({7, 7, 7, 7, 7, 7}) -> 1

Your Answer:

Feedback

Your feedback will appear here when you check your answer.