zoukankan      html  css  js  c++  java
  • LC 406. Queue Reconstruction by Height

    Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

    Note:
    The number of people is less than 1,100.

    Example

    Input:
    [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
    
    Output:
    [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

    Runtime: 32 ms, faster than 52.69% of C++ online submissions for Queue Reconstruction by Height.

    按身高降序排列,身高相同的按第二个数升序排列。

    然后我们一个一个按照第二个数的index插入一个新的序列。这样做的好处是,插入后面的数不会对之前的数产生

    影响。

    但这种做法需要新开一个数组,如果你不想新开一个数组,可以在当前数组种修改,但如果是vector其实提升效果一般吧,最好开一个链表。

    #include <assert.h>
    #include <map>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #define ALL(x) (x).begin(), (x).end()
    using namespace std;
    class Solution {
    public:
      static bool sortcmp(const pair<int,int> a, const pair<int,int> b){
        if(a.first == b.first) return a.second < b.second;
        return a.first > b.first;
      }
      vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int,int>> ret;
        if(people.empty()) return ret;
        sort(ALL(people), sortcmp);
        for(int i=0; i<people.size(); i++){
          ret.insert(ret.begin() + people[i].second, people[i]);
        }
        return ret;
      }
    };
  • 相关阅读:
    摄影基础知识(二)
    std::bind
    摄影网站汇总
    std::function
    常用路径说明
    摄影基础知识(一)
    JavaScript 箭头函数:适用与不适用场景
    软帝学院:Java实现的5大排序算法
    软帝学院:用Java编写计算器,代码展示!
    windows环境下运行java的脚本
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10190940.html
Copyright © 2011-2022 走看看