コード例 #1
0
Ptr getMaxTree(const Arr<T>& data) {
	if (data.empty()) return nullptr;

	Arr<Ptr> node(data.size(), nullptr);
	for(int i = 0; i < data.size(); ++i)
		node[i] = std::make_shared<TreeNode>(data[i]);

	HashMap MaxMap;
	std::stack<Ptr> s;

	for (int i = 0; i < data.size(); ++i) {
		auto cur = node[i];
		while (!s.empty() && s.top()->value < data[i]) {
			popStackSetMap(s, MaxMap, cur);
		}
		s.push(node[i]);
	}
	while (!s.empty()) {
		popStackSetMap(s, MaxMap, nullptr);
	}

	Ptr head = nullptr;

	for (int i = 0; i < node.size(); ++i) {
		auto cur = node[i];
		auto res = MaxMap.find(cur);
		//结构如下  node  left right
		//node是当前访问节点  left是左边离他最近比node大的点,right是右边。。
		//nullptr代表没有或者到达边界
		if (!res->second.first && !res->second.second) {
			head = res->first;
		}
		else if (!res->second.first) {
			if (!res->second.second->left) {
				res->second.second->left = res->first;
			}
			else {
				res->second.second->right = res->first;
			}
		}
		else if (!res->second.second) {
			if (!res->second.first->left) {
				res->second.first->left = res->first;
			}
			else {
				res->second.first->right = res->first;
			}
		}
		else {
			auto tmp = res->second.first->value < res->second.second->value ? res->second.first : res->second.second;
			if (!tmp->left) {
				tmp->left = res->first;
			}
			else {
				tmp->right = res->first;
			}
		}
	}
	return head;
}
コード例 #2
0
std::pair<int, int> getMinMax(const Arr& data) {
	int maxNum = INT_MIN;
	int minNum = INT_MAX;

	if (data.size() & 0x1)
		maxNum = minNum = data.back();

	for (int i = 0; i + 1< data.size(); i+=2) {
		if (data[i] < data[i + 1]) {
			minNum = data[i] > minNum ? minNum : data[i];
			maxNum = data[i+1] < maxNum ? maxNum : data[i+1];
		}
		else {
			minNum = data[i + 1] > minNum ? minNum : data[i + 1];
			maxNum = data[i] < maxNum ? maxNum : data[i];
		}
	}
	return { minNum, maxNum };
}