Build a Point class whose points compare by their values. Then use it to count the different points in a list.
You get the list of points. Some points appear more than once. Return how many different points it holds.
Write:
- a class
Point, created bynew Point(x, y). Two points are equal when theirxand theiryboth match. - a method
countUnique(points)in the classSolution. It returns the number of different points.
In Java, override equals and hashCode, as in Comparing Objects. Then add the points themselves to a HashSet. The set uses your two methods to drop the repeats.
The program also checks your class directly. It compares a point with a copy of itself, and with the points next to it.
Example 1:
Input: points = [(1, 2), (3, 4), (1, 2)] Output: 2 Explanation: (1, 2) appears twice. It is still one point. (3, 4) is the other one.
Example 2:
Input: points = [(2, 1), (1, 2)] Output: 2 Explanation: The same two numbers in another order make another point.
Example 3:
Input: points = [(0, 0), (0, 0), (0, 0), (0, 0)] Output: 1 Explanation: All four are the same point.
Constraints:
- 1 to 1,000 points.
- Each coordinate is a whole number from -1,000 to 1,000.
A set adds a point in O(1) time on average. So counting n points takes O(n).
Free plan: 30 tutor messages. Premium is unlimited.
