Algorithm problem: a ascending from the array, look for two numbers, two numbers equals the number of inputs.

Microsoft 100 ----- Enter a title algorithm has been sorted in ascending order and a digital array to find two numbers in the array, so that their sum is just the digital inputs. Requirements: time complexity is O (n). If there are multiple equal to the digital input and the digital output of any one pair.

Ideas: setting two pointers, a pointer to the beginning, a point at the end, the two numbers together, and if the big, the pointer on the right to the left, and if small, then the pointer to the left to the right.

int main(void)
{
	int arry[] = {1, 3, 4, 6, 7, 8, 9};
	int key = 11;
	int len = sizeof(arry)/sizeof(arry[0]);
	int i, sum;
	int *head = &arry[0];
	int *tail = &arry[len-1];
	for(i=0; i<len/2; i++)
	{
		sum = *(head) + *(tail);
		if(sum > key)
		{
			tail--;
		}
		else if(sum < key)
		{
			head++;
		}
		else if(key == sum)
		{
			printf("%d + %d\n", *(head), *(tail));
		}
		else 
			printf("该数组中没有两数之和满足条件\n");
	}
	return 0;
}
Published 50 original articles · won praise 5 · Views 1533

Guess you like

Origin blog.csdn.net/qq_42483691/article/details/104565570