第一章 緒論
1.回圈左移
void reverseArr(int A[],int start,int rear)
{
for(int i=start,j=rear;i<=(start+rear)/2;i++,j++)
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
2.奇偶數排列
思路:分別設定作業指標i和j,i指向陣列的低地址端,j指向陣列的高地址端,一旦發現左邊是偶數,右邊是奇數,則發生交換,
void split(int A[],int n)
{
for(int i=0,j=n-1;i<j;i++,j--)
{ //前奇后偶,正常i++,j--
if(A[i]%2==0 && A[j]%2==1) //前偶后奇,交換位置
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
else if(A[i]%2==0 && A[j]%2==0) i--; //前偶后偶,i繼續停留在原來位置,不能讓i后移
else if(A[i]%2==1 && A[j]%2==1) j++; //前奇后奇,j繼續停留在原來位置,不能讓j前移
}
}
3.回文字串
#include <iostream>
using namespace std;
bool judge(string str)
{
int n=str.length();
for(int i=0;i<n/2;i++)
{
if(str[i]==str[n-1]) n--; //從前往后,從后往前,一起遍歷
else return false;
}
retrun true;
}
int main()
{
string s;
getline(cin,s);
bool res=judge(s);
if(res) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
4.求最大值和次大值
#include <iostram>
using namespace std;
void getmax(int A[],int n,int &fmax,int &smax)
{
fmax=0;
smax=0;
for(int i=0;i<n;i++)
{
if(fmax<A[i])
{
smax=fmax;
fmax=A[i];
}
else if(smax<A[i]) //else if陳述句里,fmax>=A[i]
{
smax=A[i];
}
}
}
int main()
{
int n,maxV,nMax;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
getMax(a,n,maxV,nMax);
cout<<maxV<<" "<<nMax<<endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/221368.html
標籤:其他
上一篇:Swapping Places(字典序最小拓撲排序)
下一篇:練習1-遞推等
