编程题第一课

第一题

有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对。请设计一个高效的算法,计算给定数组中的逆序对个数。

给定一个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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值