在已排序的數組中尋找和是給定值的兩項,要求時間複雜度爲O(n)

// 在已排序的數組中尋找和是給定值的兩項.cpp : Defines the entry point for the console application.
//
/*
1.最簡單的思路是固定數組中的一個數,然後尋找其餘n-1個數看是否有滿足條件的,時間複雜度是O(n^2)

2.另一種思路:由於數組是有序的,我們從數組的兩端開始,如果和大於給定的值,則尾端的數向後移動一步,如果和小於給定值
則首端的數向前移動一步,這樣直到找到滿足條件的兩個數,或者首尾到達同一位置還未找到,退出

*/
#include "stdafx.h"
#include <iostream>
using namespace std;
void FindTwoNums(int array[],int length,int total)
{
	int head=0;
	int tail=length-1;
	int sum;
	while(head!=tail)
	{
		sum=array[head]+array[tail];
		if(sum>total)
			tail--;
		else if(sum<total)
			head++;
		else
			break;	
	}
	if(head!=tail)
	{
		cout<<array[head]<<","<<array[tail]<<endl;
	}
	else
	{
		cout<<"未找到這兩個數"<<endl;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	int array[]={1,4,6,7,9,15,20,27,30,35};
	FindTwoNums(array,10,26);
	FindTwoNums(array,10,28);
	FindTwoNums(array,10,32);
	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章