第一题
有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对。请设计一个高效的算法,计算给定数组中的逆序对个数。
给定一个int数组A和它的大小n,请返回A中的逆序对个数。保证n小于等于5000。
测试样例:
[1,2,3,4,5,6,7,0],8
返回:7
答案:
/*
冒泡排序时做了多少次交换就有多少个逆序
*/
class AntiOrder {
public:
int count(vector<int> A, int n) {
// write code here
int count = 0;
int i,j;
if(n < 2) return n;
for(i=0;i<n;i++){
for(j=0;j<n-i-1;j++){
if(A[j]>A[j+1]){
swap(A[j],A[j+1]);
count++;
}
}
}
return count;
}
};
题目二:
写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。
例如输入:
abcd
输出
dcba
答案:
//最简洁
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
for(int i = str.size()-1; i >=0;i--)
cout << str[i];
}
方法二:利用栈
//这样的输出可以利用栈后进先出的结构
#include<iostream>
#include<stack>
using namespace std;
int main(void)
{
char ch;
stack<char> ch_stack;
while(cin>>ch)
{
ch_stack.push(ch);
}
while(!ch_stack.empty())
{
cout<<ch_stack.top();
ch_stack.pop();
}
return 0;
}
方法三:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
cin >> str;
reverse(str.begin(), str.end());
cout << str;
return 0;
}