栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【华为机试之C++】合并表记录

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【华为机试之C++】合并表记录

描述

数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。

提示:
0 <= index <= 11111111
1 <= value <= 100000

输入描述:

先输入键值对的个数n(1 <= n <= 500)
接下来n行每行输入成对的index和value值,以空格隔开

输出描述:

输出合并后的键值对(多行)

示例1
输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
示例2
输入:
3
0 1
0 2
8 9
输出:
0 3
8 9
思路
  1. 看到键值对,并且最后还要以升序的方式输出,第一反应就是使用std::map。std::map的第三个模板参数就是用于指定如何排序的,默认为less(key),即按键值升序排列。
代码

Combiner.h

#pragma once
#include 

class Combiner
{
public:
	static Combiner* getInstance();

public:
	void combine();

private:
	Combiner() = default;
	~Combiner() = default;

private:
	static Combiner* instance;
	static std::mutex iMutex;
};

Combiner.cpp

#include 
#include 
#include 
#include "Combiner.h"

Combiner* Combiner::instance = nullptr;
std::mutex Combiner::iMutex;

Combiner* Combiner::getInstance()
{
	std::unique_lock lock(iMutex);
	if (nullptr == instance) {
		instance = new Combiner();
	}

	return instance;
}

void Combiner::combine()
{
	
	uint32_t count = 0;
	std::cin >> count;

	uint32_t index = 0;
	uint32_t value = 0;

	std::map mapTable; //按KEY升序
	//std::map> mapTable;//按KEY降序
	mapTable.clear();

	while (count) {
		std::cin >> index >> value;

		
		if (index > 11111111) {
			std::cout << "An index greater than 11111111" << std::endl;
			continue;
		}

		if (value < 1 || value > 100000) {
			std::cout << "A value less than 1 or greater than 100000" << std::endl;
			continue;
		}

		
		
		auto idx = mapTable.begin();
		for (; idx != mapTable.end(); idx++) {
			if (index == idx->first) {
				idx->second += value;
				break;
			}
		}

		if (idx == mapTable.end()) {
			mapTable[index] = value;
		}

		count--;
	}

	
	for (auto& ele:mapTable) {
		std::cout << ele.first << " " << ele.second << std::endl;
	}
}

main.cpp

#include "Combiner.h"

int main(int argc, char** argv)
{
	auto combiner = Combiner::getInstance();

	combiner->combine();

	return 0;
}
测试 测试环境

visual studio 2019

测试结果
输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
输入:
3
0 1
0 2
8 9
输出:
0 3
8 9
输入:
5
1 1
2 3
1 3
2 5
输出:
1 4
2 8
5 7
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/947457.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号