前言:新手小白想学算法,顺便记录一下自己做的题。
题目:一个长度为n(n>0)的序列中存在“有趣的跳跃”是指:当且仅当相邻元素的差的绝对值经过排序后正好是从1到(n-1)。例如,1 4 2 3存在“有趣的跳跃”,因为差的绝对值分别为3,2,1。当然,任何只包含单个元素的序列一定存在“有趣的跳跃”。你需要写一个程序判定给定序列是否存在“有趣的跳跃”。
我的答案:(可能这是暴力解法?我不懂..但至少做出来了...有点小激动🤩)
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
int m;
cout<<"The number of array elements:";
cin>>m;
int array[m];
int b[m],i=0;
if (m!=1)
{
for (int n = 0; n<= m-1; n++)
{
cin >> array[n];
}
for (i=0;i<m-1;i++)
{
b[i] = abs( array[i] - array[i+1] );
cout<<b[i]<<" ";
}
sort ( b, b + (m-1) );
if ( abs(b[i]-b[i+1]) - abs(b[i+1]-b[i-2]) == 1)
{
cout<<"yes";
}
else
{
cout<<"no" ;
}
}
else // b[i]==a[i] ?
{
cin >> array[m];
cout<<array[m]<<" yes";
}
return 0;
}