统计前面比自己小的数的个数-LintCode
来源:互联网 发布:肩颈按摩仪 知乎 编辑:程序博客网 时间:2024/05/17 23:17
给定一个整数数组(下标由 0 到 n-1, n 表示数组的规模,取值范围由 0 到10000)。对于数组中的每个 ai 元素,请计算 ai 前的数中比它小的元素的数量。
注意事项:
We suggest you finish problem Segment Tree Build, Segment Tree Query II and Count of Smaller Number first.
样例:
对于数组[1,2,7,8,5] ,返回 [0,1,2,3,2]
#ifndef C249_H#define C249_H#include<iostream>#include<vector>using namespace std;class SegmentNode{public: int start, end, count; SegmentNode *left, *right; SegmentNode(int start, int end) { this->start = start, this->end = end, this->count = 0; this->left = this->right = NULL; }};class Solution {public: /* * @param A: an integer array * @return: A list of integers includes the index of the first number and the index of the last number */ vector<int> countOfSmallerNumberII(vector<int> &A) { // write your code here vector<int> v; SegmentNode *node = build(0, 10000); for (int i = 0; i<A.size(); ++i) { v.push_back(query(node, 0, A[i] - 1)); modify(node, A[i]); } return v; } SegmentNode *build(int start, int end) { if (start > end) return NULL; SegmentNode *node = new SegmentNode(start, end); if (start == end) return node; node->left = build(start, (start + end) / 2); node->right = build((start + end) / 2 + 1, end); return node; } void modify(SegmentNode *root, int index) { if (!root) return; if (root->start == root->end&&root->start==index) { root->count++; return; } int mid = (root->start + root->end) / 2; if (index<=mid) modify(root->left, index); else modify(root->right, index); root->count = root->left->count + root->right->count; } int query(SegmentNode *root, int start, int end) { if (start > end || root == NULL || start<root->start || end>root->end) return 0; if (start == root->start&&end == root->end) return root->count; if (end <= root->left->end) return query(root->left, start, end); else if (start >= root->right->start) return query(root->right, start, end); else { int l = query(root->left, start, root->left->end); int r = query(root->right, root->right->start, end); return l + r; } }};#endif
阅读全文
0 0
- LintCode:统计前面比自己小的数的个数
- 统计前面比自己小的数的个数-LintCode
- LintCode统计前面比自己小的数的个数(线段树)
- LINTCODE——统计前面比自己小的数的个数
- 统计前面比自己小的数的个数
- 统计前面比自己小的数
- Arithmetic problem | 统计前面比自己小的数的个数
- LintCode-统计比给定整数小的数的个数
- Lintcode : 统计比给定整数小的数的个数
- LintCode:统计比给定整数小的数的个数
- 统计比给定整数小的数的个数 -Lintcode
- lintcode(248)统计比给定整数小的数的个数
- 一个数组中列出一个数比前面数大,比后面数小的集合
- Inversion Sequence 已知逆序数(前面比它大的数的个数),还原数组
- 乱序数组找出前面的都比他小后面的都比他大的数
- hdu4417 树状数组(求指定区间比指定数小的数的个数)
- 求任意区间里比x小的数的个数(树状数组)
- 统计二进制数1的个数
- jdbctemplate中用in查询用法
- websocket、短连接长连接以及轮询简介
- redis实现消息队列
- Android:在程序运行时申请权限(第一行代码android)
- mongodb各种操作命令
- 统计前面比自己小的数的个数-LintCode
- Android 6.0动态申请权限
- BZOJ4170 极光 [二维线段树]
- 形象解释PID算法+PID算法源代码
- 深度学习硬件指南(号称最全)
- 解决“未能加载文件或程序集“netfx.force.conflicts”或它的某一个依赖项”
- 异常(一)
- GKQuadtree
- JSTL格式化日期