• 【慢慢学算法】:数组排序(一题多做)


    题目描述:

    输入一个数组的值,求出各个值从小到大排序后的次序。

    输入:

    输入有多组数据。
    每组输入的第一个数为数组的长度n(1<=n<=10000),后面的数为数组中的值,以空格分割。

    输出:

    各输入的值按从小到大排列的次序(最后一个数字后面没有空格)。

    样例输入:
    4
    -3 75 12 -3
    样例输出:
    1 3 2 1
    //单纯使用map,利用map中键唯一的特性
    #include<iostream>
    #include<map>
    #include<algorithm>
    using namespace std;
    int A[10010], B[10010];
    int main()
    {
        int n;
        while(cin >> n)
        {
    	map<int,int> m;   
    	for(int i = 0; i < n; i++)
    	{
    	    cin >> A[i];
    	    B[i] = A[i];
    	}
    	sort(B, B+n);
    	int index = 0;
    	for(int i = 0; i < n; i++)
    	{
    	    m.insert(pair<int,int>(B[i], index++));
    	    if( i!=0 && B[i] == B[i-1])
    		index--;
    	}
    	cout << m.find(A[0])->second+1 ;
    	for(int i = 1; i < n; i++)
    	    cout << " " << m.find(A[i])->second+1;
    	cout << endl;
    
        }
        
        return 0;
    }
    

      

    //利用顺序容器vector以及unique算法,效率更高
    #include<iostream>
    #include<map>
    #include<algorithm>
    #include<vector>
    using namespace std;
    int main()
    {
        int n;
        while(cin >> n)
        {
    	vector<int> A(n);
    	map<int,int> m;
    	vector<int>::iterator iter = A.begin();
    	for(; iter != A.end(); iter++)
    	    cin >> *iter;
    	vector<int> B(A);
    	sort(B.begin(), B.end());
    	iter = unique(B.begin(), B.end());
    	B.erase(iter,B.end());
    	for(int i = 0; i < n; i++)
    	{
    	    m.insert(pair<int,int>(B[i], i));
    	}
    	cout << m.find(A[0])->second+1 ;
    	for(int i = 1; i < n; i++)
    	    cout << " " << m.find(A[i])->second+1;
    	cout << endl;
        }
        return 0;
    }
    

      

     list

      list<int> l

      插入:push_back尾部,push_front头部,insert方法前往迭代器位置处插入元素,链表自动扩张,迭代器只能使用++--操作,不能用+n -n,因为元素不是物理相连的。

      遍历:iterator和reverse_iterator正反遍历

      删除:pop_front删除链表首元素;pop_back()删除链表尾部元素;erase(迭代器)删除迭代器位置的元素,注意只能使用++--到达想删除的位置;remove(key) 删除链表中所有key的元素,clear()清空链表。

      查找:it = find(l.begin(),l.end(),key)

      排序:l.sort()

       删除连续重复元素:l.unique() 【2 8 1 1 1 5 1】 --> 【 2 8 1 5 1】

    给梦想一点时间
  • 相关阅读:
    asp.net页面生命周期追踪
    asp.net Forums 之配置,缓存,多数据访问
    沪江技术部程序员招聘试题,大家一起讨论一下。
    httpd does not appear to be running and proxying cobbler, or SELinux is in the way.
    网络知识OSI七层网络与TCP/IP五层网络架构及二层/三层网络
    python中用psutil模块,yagmail模块监控CPU、硬盘、内存使用,阈值后发送邮件
    Linux中访问Apache报403错误处理方法
    centos7的启动流程
    pycharm介绍
    监测NGINX服务的shell脚本
  • 原文地址:https://www.cnblogs.com/VortexPiggy/p/2591189.html
Copyright © 2020-2023  润新知