315. 计算右侧小于当前元素的个数(C++)---线段树解题

题目详情

给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是  nums[i] 右侧小于 nums[i] 的元素的数量。

示例:

输入: [5,2,6,1]
输出: [2,1,1,0] 
解释:
5 的右侧有 2 个更小的元素 (2 和 1).
2 的右侧仅有 1 个更小的元素 (1).
6 的右侧有 1 个更小的元素 (1).
1 的右侧有 0 个更小的元素.


——题目难度:困难


 





-解题代码

struct SegmentTreeNode {
	int start;
	int end;
	int count;
	
	SegmentTreeNode* left;
	SegmentTreeNode* right;
	
	SegmentTreeNode(int _start, int _end):start(_start),end(_end),count(0) {
		left = NULL;
		right = NULL;
	}	
};

class Solution {
public:
	SegmentTreeNode* build(int min, int max) {
		SegmentTreeNode* root = new SegmentTreeNode(min, max);
		
		if (min != max) {
			int mid = min + (max - min) / 2;
			root->left = build(min, mid);
			root->right = build(mid+1, max);
		}
		
		return root;
	}
	
	int count(SegmentTreeNode* root, int start, int end) {
		if (start > end) return 0;
		if (root->start == start && root->end == end) {
			return root->count;
		}
		
		int mid = root->start + (root->end - root->start) / 2;
		int leftcount = 0, rightcount = 0;
		
		if (start <= mid) {
			if (end > mid) 
				leftcount = count(root->left, start, mid);
			else 
				leftcount = count(root->left, start, end);
		}
		
		if (end > mid) {
			if (start <= mid) 
				rightcount = count(root->right, mid + 1, end);
			else 
				rightcount = count(root->right, start, end);
		}
		
		return leftcount + rightcount;
	}
	
	void insert(SegmentTreeNode* root, int num) {
		if (root->start == num && root->end == num) {
			root->count++;
			return ;
		}
		
		int mid = root->start + (root->end - root->start) / 2;
		if (num <= mid) 
			insert(root->left, num);
		if (num > mid) 
			insert(root->right, num);
		
		root->count = root->left->count + root->right->count;
	}
		
				
    vector<int> countSmaller(vector<int>& nums) {
		vector<int> ans;
		if (nums.empty()) return ans;
		
		int minNum = nums[0], maxNum = nums[0], n = nums.size();
		ans.resize(n);
		for(int i = 1; i < n; i++) {
			minNum = min(minNum, nums[i]);
			maxNum = max(maxNum, nums[i]);
		}
		
		SegmentTreeNode* root = build(minNum, maxNum);
		for(int i = n - 1; i >= 0; i--) {
			ans[i] = count(root, minNum, nums[i] - 1); //找[min, nums[i] - 1]的元素个数,也就是小于 nums[i] 的元素个数
			insert(root, nums[i]);
		}
		
		return ans;	
    }
};

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重剑DS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值