// 2_16.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #define INT_MIN -1000000; int binary_search(int *a,int len,int n)//若返回值为x,则a[x]>=n>a[x-1] { int left=0,right=len-1,mid=(left+right)/2; while(left<=right) { if(n>a[mid]) left=mid+1; else if(n<a[mid]) right=mid-1; else return mid; mid=(left+right)/2; } return left; } int LIS(int * arr, int len) { int * max = new int[len+1]; int * lis = new int[len]; max[0] = INT_MIN; max[1] = arr[0]; int maxLis = 1; for(int i=0;i<len;i++) { //遍历 /*for(int j=maxLis;j>=0;j--) { if(arr[i] > max[j]) { lis[i] = j+1; break; } }*/ //二分查找 lis[i] = binary_search(max,maxLis+1,arr[i]); if(lis[i] > maxLis) { max[lis[i]] = arr[i]; maxLis = lis[i]; } else if(max[lis[i]-1] < arr[i] && arr[i] < max[lis[i]]) { max[lis[i]] = arr[i]; } } delete [] max; delete [] lis; return maxLis; } int _tmain(int argc, _TCHAR* argv[]) { int arr[] = {1,2,5,4,6}; printf("%d\n", LIS(arr,5)); return 0; }