Leetcode Count of Smaller Numbers after self

Source: Internet
Author: User

Topic Connection

https://leetcode.com/problems/count-of-smaller-numbers-after-self/

Count of Smaller Numbers after selfdescription

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

Example:

Given $nums = [5,2,6,1]$
The right of 5 there is 2 smaller elements (2 and 1).
The right of 2 there are only 1 smaller element (1).
The right of 6 there is 1 smaller element (1).
The right of 1 there is 0 smaller element.
Return the array $[2, 1, 1, 0]$.

Line tree to find the number of reverse, first discretization, and then using line tree statistics.

Class Solution {Private:typedef vector<int> Vec;public:vec countsmaller (vec& nums) {VEC ans;int n = 0;if (!) ( n = nums.size ())) return Ans;ans.resize (n, 0), ret = new P[n + 10];for (int i = 1; I <= n; i++) Ret[i] = P (nums[i-1), i); sort (ret + 1, ret + n + 1), SEG = new int[(n + +) << 2];memset (seg, 0, sizeof (int) * ((n + 2) <<)); for (i NT i = 1; I <= N; i++) {int v = query (1, 1, N, Ret[i].id, N), insert (1, 1, N, ret[i].id); ans[ret[i].id-1] = v;} delete[]seg; Delete[]ret;return ans;} private:struct P {int V, id;  P (int _i_ = 0, int _j_ = 0): V (_i_), id (_j_) {}friend bool operator< (const p &a, const p &b) {return A.V = B.V ? a.ID < B.ID:A.V < B.V;}}  *ret;int *seg;inline void Insert (int root, int l, int r, int p) {if (P > R | | p < l) return;if (P <= L && P >= r) {seg[root]++; return;} int mid = (L + R) >> 1;insert (Root << 1, L, Mid, p); Insert (Root << 1 | 1, mid + 1, r, p); Seg[root] = seg [Root << 1] + SEg[root << 1 | 1];} inline int query (int root, int l, int r, int x, int y) {if (x > R | | y < L) return 0;if (x <= l && y >  = r) return seg[root];int ret = 0;int mid = (L + R) >> 1;ret + = query (Root<<1, L, Mid, X, y); ret + = query (root << 1 | 1, Mid + 1, r, X, y); return ret;}};

Leetcode Count of Smaller Numbers after self

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.