Number of good number pairs for the algorithm

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 as 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 groups of good number pairs, namely (0,3), (0,4), (3,4), (2,5), and 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

Algorithm 1: Use double-layer loop to directly traverse statistics, similar to bubble sort

void Fun(int *arr,int length)//o(n^2) o(1)
{
    
    
	int num = 0;
	for (int i = 0; i < length; ++i)
	{
    
    
		for (int j = i + 1; j < length; ++j)
		{
    
    
			if (arr[i] == arr[j])
			{
    
    
				++num;
			}
		}
	}
	printf("%d", num);
}

Algorithm 2: Use an iterator to traverse the array, equal to +1

int GoodNumberPair(vector<int>& nums)
{
    
    
	int cnt = 0;
	for (auto i = nums.begin(); i != nums.end(); i++)	// 使用迭代器遍历
	{
    
    
		for (auto j = i+1; j!=nums.end(); j++)			// 遍历
		{
    
    
			if (*i == *j) cnt++;						// 相等加一
		}
	}
	return cnt;
}

// 打印数组
void Print(vector<int>& vec)
{
    
    
	for (auto v : vec)
	{
    
    
		cout << v << " ";
	}
	cout << endl;
}

Test code:

int main()
{
    
    
	vector<int> test1{
    
     1,2,3,1,1,3 };
	auto ret1 = GoodNumberPair(test1);

	vector<int> test2{
    
     1,1,1,1 };
	auto ret2 = GoodNumberPair(test2);

	vector<int> test3{
    
     1,2,3 };
	auto ret3 = GoodNumberPair(test3);


	Print(test1);
	cout << ret1 << endl;
	Print(test2);
	cout << ret2 << endl;
	Print(test3);
	cout << ret3 << endl;

    /*
    int arr[] = {1,1,1,1};
	int length = sizeof(arr) / sizeof(arr[0]);
	Fun(arr, length);
   */
	return 0;
}

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109126169