Number of good pairs: LeetCode Question 1512

Gives you an integer array nums.
If a set of numbers (i, j) satisfies nums[i] == nums[j] and i <j, it can be considered a good number pair.
Returns the number of good pairs.

Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good number pairs, namely (0,3), (0,4), (3,4 ), (2,5), the subscript starts from 0

Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each group of numbers in the array is a good number pair

Example 3:
Input: nums = [1,2,3]
Output: 0

Method 1: Brute force method

int numIdenticalPairs(int* nums, int numSize) // (时间复杂度O(n^2)  空间复杂度O(1))
{
    
    
	int count = 0;//统计好数的数目
	for (int i = 0; i < numSize; i++)
	{
    
    
		for (int j = i + 1; j < numSize; j++)
		{
    
    
			if (nums[i] == nums[j])
			{
    
    
				count++;
			}
		}
	}
	return count;
}

Method 2: Hash table method

int numIdenticalPairs(int* nums, int numsSize)
{
    
    
	int count = 0;//累积好数对的数目
	int hash[100] = {
    
     0 };

	for (int i = 0; i < numsSize; i++)
	{
    
    
		hash[nums[i]]++;//每个数目出现的次数
		count += hash[nums[i]] - 1;//如果只出现一次好数对数目为0,出现的次数大于1则依次累加
	}

	return count;
}

Guess you like

Origin blog.csdn.net/weixin_45824959/article/details/112986171