public class A{
private A(){}//把构造函数设为private,其它类就不能再调用实例化
private static A instance=new A();//惟一的一个实例,加上static属性
public static A getInstance(){//其它类调用A的惟一入口,也是static属性,调用方法是A.getInstance()
return instance;
}
}
有序数组中找出和为某值的两个数(笔试题) 时间复杂度O(n)
/*dataArray为有序数组,其中只有两个数的和为sum,以最快的方法找出这两个数*/
int sum=50;
void FindNumber(int *dataArray, int size, int *number1, int *number2)
{
int low=0, high=size-1;
int temp=dataArray[low]+dataArray[high];
while (low<high && temp!=sum)
{
while (low<high && temp<sum)
{
low++;
temp=dataArray[low]+dataArray[high];
}
while (low<high && temp>sum)
{
high--;
temp=dataArray[low]+dataArray[high];
}
}
if(temp==sum)
{
*number1=dataArray[low];
*number2=dataArray[high];
}
else
{
*number1=0;
*number2=0;
}
}
void TestFindNumber()
{
int data[10]={1, 3, 6, 8, 10, 11, 12, 35, 40, 43};
int number1, number2;//用于存储找到的两个数
FindNumber(data, 10, &number1, &number2);
printf("number1: %d\t number2: %d\n", number1, number2);
}