我正在编写一个 C++ 程序,它将查找并打印整数向量的第一个最长的升序或降序连续子序列。例如,给定一个向量
4, 2, 1, 2, 3, 4, 3, 5, 1, 2, 4, 6, 5
返回 1,2,3,4
我的代码如下:
但是,我不知道如何返回第一个最优解。例如,上面的序列有 1、2、4、6,也是 4 长。但是,我们只需要返回 1,2,3,4。
bool findLong(const vector<int> v)
{
if (v.size() <1)
return false;
if (v.size() == 1){
cout << v[0] << endl;
return true;
}
vector::const_iterator itr_left, itr_right;
itr_left = v.begin();
itr_right = v.begin()+1;
bool ascending_flag ;
int counter =0;
if (*itr_right > *(itr_right-1)){
bool ascending_flag = true;
++ascending_counter;
}
else{
bool ascending_flag = false;
++descending_counter;
}
int longest = INT_MIN;
Vector<int>::iterator longest_left = v.begin(), longest_right =v.begin();
++itr_right;
while (itr_right != v.end())
{
if (ascending_flag && *itr_right > *(itr_right-1))
++ascending_counter;
if (!ascending_flag&& *itr_right < *(itr_right-1))
++descending_counter;
if (ascending_flag&& *itr_right < *(itr_right-1))
{
if (ascending_counter > longest )
{
longest = ascending_counter;
longest_left = itr_left;
longest_right = itr_right;
}
itr_left = itr_right;
ascending_counter = 0 ;
ascending_flag = false;
}
if (ascending_flag && *itr_right > *(itr_right-1))
{
if (descending_counter > longest )
{
longest = descending_counter;
longest_left = itr_left;
longest_right = itr_right;
}
itr_left = itr_right;
descending_counter = 0 ;
ascending_flag = true;
}
++itr_right;
}
for_each( longest_left , longest_right, print);
cout << endl;
}
Void print(int i)
{
cout << i << " , " ;
}
欢迎任何意见!
谢谢 !