目录
一、题目
二、代码
(一)时间复杂度过高(通过70%)
(二)改进
一、题目
二、代码
(一)时间复杂度过高(通过70%)
#include <iostream>
#include <vector>
#include<cstdbool>
using namespace std;
bool ASC(vector<int>a, int begin, int end)
{ //升序
if (begin == end)
return true;
for (int k = begin + 1; k <= end; k++)
{
if (a[k] >= a[k - 1])
{
continue;
}
else
{
return false;
}
}
return true;
}
bool DESC(vector<int>a, int begin, int end)
{ //降序
if (begin == end)
return true;
for (int k = begin + 1; k <= end; k++)
{
if (a[k] <= a[k - 1])
{
continue;
}
else
{
return false;
}
}
return true;
}
int main() {
int n;
cin >> n;
vector<int>data;
int x;
for (int i = 0; i < n; i++) {
cin >> x;
data.push_back(x);
}
int sum = 0;
int start = 0, oldstart = -1;
int prev = 0;
int next = 0;
while (next <= n - 1)
{
if (ASC(data, start, next) || DESC(data, start, next))
{
prev = next;
++next;
continue;
}
if (start != oldstart)
{
sum += 1;
oldstart = start;
start = next;
}
}
if (start != oldstart)
{
sum += 1;
}
cout << sum;
return 0;
}
(二)改进
- 主要是将判断升序和降序的代码合并成了一个!!!
bool isSort(vector<int>& a, int begin, int end, bool increasing)
{
if (begin == end)
return true;
for (int k = begin + 1; k <= end; k++)
{
if (increasing) //升序
{
if (a[k] >= a[k - 1])
continue;
else
return false;
}
else //降序
{
if (a[k] <= a[k - 1])
continue;
else
return false;
}
}
return true;
}
完整代码
#include <iostream>
#include <cstdbool>
#include <vector>
using namespace std;
bool isSort(vector<int>& a, int begin, int end, bool increasing)
{
if (begin == end)
return true;
for (int k = begin + 1; k <= end; k++)
{
if (increasing) //升序
{
if (a[k] >= a[k - 1])
continue;
else
return false;
}
else //降序
{
if (a[k] <= a[k - 1])
continue;
else
return false;
}
}
return true;
}
int main() {
int n;
cin >> n;
vector<int> data;
int x;
for (int i = 0; i < n; i++)
{
cin >> x;
data.push_back(x);
}
int sum = 0;
int start = 0, oldstart = -1;//oldstart用于表示上一次有序子序列开始的下标
int prev = 0;
int next = 0;
while (next <= n - 1)
{
if (isSort(data, start, next, true) || isSort(data, start, next, false))
{
prev = next;
++next;
continue;
}
if (start != oldstart) {
sum += 1;
oldstart = start;
start = next;
}
}
if (start != oldstart) //跳出循环,最后一个子序列的判断
{
sum += 1;
}
cout << sum;
return 0;
}