华为机试:寻找数组中A=B+2C的组合

寻找给定数组中A=B+2C的组合,(只返回满足条件的任意一组即可)重复数字不算,若不存在这个组合返回0。

如给定数组【2 7 3 0】,返回 7,3,2

int* FindABC(int*arr, int len)
{
	int * res = (int*)malloc(3 * sizeof(int));
	//A=B+2C
	int A = 0, B = 0, C = 0;
	for (size_t i = 0; i < len; i++)//固定第一个数
	{
		for (size_t j = 0; j < len; j++)//固定第二个数
		{
			if (j == i)
				continue;

			for (size_t k = 0; k < len; k++)//查找第三个数
			{
				if (j == k || k==i)
					continue;
				if (arr[i] != arr[j] && arr[j] != arr[k] && arr[i] != arr[k])
				{
					if (arr[i] ==( arr[j] + 2 * arr[k]))
					{
						A = arr[i];
						B = arr[j];
						C = arr[k];
					}
					if (arr[i] == (arr[k] + 2 * arr[j]))
					{
						A = arr[i];
						B = arr[k];
						C = arr[j];
					}
					if (arr[j] == (arr[i] + 2 * arr[k]))
					{
						A = arr[j];
						B = arr[i];
						C = arr[k];
					}
					if (arr[j] == (arr[k] + 2 * arr[i]))
					{
						A = arr[j];
						B = arr[k];
						C = arr[i];
					}
					if (arr[k] == (arr[i] + 2 * arr[j]))
					{
						A = arr[k];
						B = arr[i];
						C = arr[j];
					}
					if (arr[k] == (arr[j] + 2 * arr[i]))
					{
						A = arr[k];
						B = arr[j];
						C = arr[i];
					}
				}
			}
	
		}
	}
	if (A != 0)
	{
		res[0] = A;
		res[1] = B;
		res[2] = C;
		return res;
	}
	else
	{
		free(res);
		return NULL;
	}
	
}

你可能感兴趣的:(C/C++,LeetCode,算法)