码迷,mamicode.com
首页 > 编程语言 > 详细

算法 - 求一个数组的最长递减子序列(C++)

时间:2017-06-17 13:08:27      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:oid   target   longest   space   assert   std   sea   tracking   ace   

//****************************************************************************************************
//
//  求一个数组的最长递减子序列 - C++ - by Chimomo
//
//  题目: 求一个数组的最长递减子序列,比方{8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}的最长递减子序列为{14。8,3。2,1}。
//
//  Answer: Scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can be substituted.
//
//****************************************************************************************************

#include <iostream>
#include <cassert>
#include <stack>

using namespace std ;

int BinarySearch(int *A, int nTarget, int nLen);

// Find the longest decreasing sequence in array A of length nLen.
void FindLongestDecreasingSequence(int *A, int nLen)
{
	int *index = new int[nLen];
	int *LDS = new int[nLen];
	index[0] = A[0];
	LDS[0] = 1;
	int indexLen = 1;

	for (int i = 1; i < nLen; i++)
	{
		int pos = BinarySearch(index, A[i], indexLen);
		index[pos] = A[i];
		LDS[i] = pos + 1;
		if(pos >= indexLen)
		{
			indexLen++;
		}
	}

	int ResultLen = indexLen;

	for (int i = nLen; i >= 0; i--)
	{
		if(LDS[i] == ResultLen)
		{	
			index[ResultLen - 1] = A[i];
			ResultLen--;
		}		
	}

	for (int i = 0; i < indexLen; i++)
	{
		cout << index[i] << " ";
	}

	delete [] index;
}

// Binary search nTarget in array A of length nLen.
int BinarySearch(int *A, int nTarget, int nLen)
{
	assert(A != NULL && nLen > 0);
	int start = 0;
	int end = nLen - 1;

	while (start <= end)
	{
		int mid = (start + end) / 2;

		if(nTarget > A[mid])
		{
			end=mid-1;
		}
		else if(nTarget<A[mid])
		{
			start=mid+1;
		}
		else
		{
			return mid;
		}
	}

	return start;
}

int main()
{
	int A[] = {8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1};
	int nLen = sizeof(A) / sizeof(int);
	FindLongestDecreasingSequence(A, nLen);
	return 0;
}

// Output:
/*
14 8 7 6 2 1
*/

算法 - 求一个数组的最长递减子序列(C++)

标签:oid   target   longest   space   assert   std   sea   tracking   ace   

原文地址:http://www.cnblogs.com/claireyuancy/p/7039837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!