求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。

int binaryFind(int* lis, int target, int end) {
	int low = 0;
	int high = end;
	while (low <= high) {
		int mid = (low + high) / 2;
		if (target < lis[mid]) {
			low = mid + 1;
		} else {
			high = mid - 1;
		}
	}
	return low;
}

int* findLongestSubquence(int* arr, int len, int &maxLen) {
	if (!arr || len == 0) {
		return NULL;
	}
	//0~i元素递减排序
	int* lis = new int[len];
	//记录i元素结尾的递减子序列长度
	int* lds = new int[len];
	memset(lis, 0, sizeof(int) * len);
	memset(lds, 0, sizeof(int) * len);

	maxLen = 1;
	lis[0] = arr[0];
	lds[0] = 1;

	for (int i = 1; i < len; ++i) {
		//递减的二分查找
		int pos = binaryFind(lis, arr[i], maxLen - 1);
		lis[pos] = arr[i];
		//以该元素结尾的最长递减序列的长度
		lds[i] = pos + 1;

		if (pos >= maxLen) {
			maxLen++;
		}
	}

	int curLen = maxLen;
	//还原最长递减子序列
	for (int i = len - 1; i >= 0; --i) {
		if (lds[i] == curLen) {
			lis[curLen - 1] = arr[i];
			curLen--;
			if (curLen == 0) {
				break;
			}
		}
	}
	return lis;
}

你可能感兴趣的:(算法-数组)