564.Count Pairs with Equal Values
Easy
Given an array
nums, return how many pairs of positions i < j hold equal values.
This problem puts O(n)Linear Time O(n)Work proportional to the input size. and O(n²)Quadratic Time O(n²)Work proportional to the square of the input size. side by side. Checking every pair takes n(n − 1)/2 comparisons; remembering counts in a map turns the job into one pass. For 1000 values that is about 500,000 steps versus 1000; for a million values it is the difference between hours and a fraction of a second. The faster version trades extra memory for time — a very common bargain.
Example 1:
Input: nums = [4,7,4,4,7]
Output: 4
Example 2:
Input: nums = [1,2,3]
Output: 0
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 1000 - ●
-1000000 ≤ nums[i] ≤ 1000000
nums =
[4, 7, 4, 4, 7]