zoukankan      html  css  js  c++  java
  • 315. Count of Smaller Numbers After Self

    You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

    Example:

    Given nums = [5, 2, 6, 1]

     

    To the right of 5 there are 2 smaller elements (2 and 1).

    To the right of 2 there is only 1 smaller element (1).

    To the right of 6 there is 1 smaller element (1).

    To the right of 1 there is 0 smaller element.

    Return the array [2, 1, 1, 0].

     

    Solution1: tranverse the nums array starting from the last number, insert the number into the already ordered vector t, the index of the number in t is just counts[i]. Here use the binary search to implement the insertion.

    class Solution {
    public:
        vector<int> countSmaller(vector<int>& nums) {
            vector<int> t, res(nums.size());
            for (int i = nums.size() - 1; i >= 0; i--) {
                int left = 0, right = t.size();
                while (left < right) {
                    int mid = (left + right) / 2;
                    if (t[mid] >= nums[i]) right = mid;
                    else left = mid + 1;
                }
                res[i] = right;
                t.insert(t.begin() + right, nums[i]);
            }
            return res;
        }
    };
       

    Solution 2: line 6 use the STL function lower_bound to find the positon of the insertion, however, the time complexity is O(n^2) because of the insertion.

     1 class Solution {
     2 public:
     3     vector<int> countSmaller(vector<int>& nums) {
     4         vector<int> t, res(nums.size());
     5         for (int i = nums.size() - 1; i >= 0; i--) {            
     6             res[i] = lower_bound(t.begin(),t.end(),nums[i])-t.begin();
     7             t.insert(t.begin() + res[i], nums[i]);
     8         }
     9         return res;
    10     }
    11 };

    Solution 3:merge sort  http://blog.csdn.net/qq508618087/article/details/51320926

  • 相关阅读:
    【转】Storm并行度详解
    Storm 集群安装配置
    【原】storm源码之storm代码结构【译】
    Storm中-Worker Executor Task的关系
    Storm源码分析--Nimbus-data
    storm配置
    Nimbus<三>Storm源码分析--Nimbus启动过程
    Nimbus<二>storm启动nimbus源码分析-nimbus.clj
    Twitter Storm源代码分析之Nimbus/Supervisor本地目录结构
    linux 相关学习记录
  • 原文地址:https://www.cnblogs.com/anghostcici/p/7439886.html
Copyright © 2011-2022 走看看