知识储备:02数组与字符串:利用哈希表实现动态规划

动态规划:动态规划是通过拆分问题,定义问题状态和状态之间的关系,使得问题能够以递推(或者说分治)的方式去解决。

在编程中,当处理当期节点的内容需要依赖之前的部分结果时,可以使用哈希表记录之前的结果,本质类似于动态规划(Dynamic Programming),利用哈希表以O(1)的时间复杂度使用之前的结果。

1.找出数组中和为某固定值的一对数

参数:数组nums,和sum

在普通的循环查找中,每个元素需要遍历数组的所有元素,时间复杂度O(n^2)。这个过程中有重复操作,如果将之前的处理过的元素加入嘻哈表,能减少多余操作,时间复杂度为O(n)。数组有m个元素,空间复杂度O(m)。

2.找出数组中最长的连续的元素序列

参数:数组nums

新建一个哈希表,逐渐检查数组中的元素,按大小决定是否加入,统一最值,最后最大值减去最小值即为所求序列长度。


#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


/*
利用哈希表实现动态规划
2017-8-16
*/

//找出数组中和为某固定值的一对数
vector<int> addsToSum(vector<int> &nums, int sum)
{
	vector<int> res(2);
	unordered_map<int, int> numsToIndex;

	for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
	{
		if (numsToIndex.count(sum - *iter))
		{
			res[0] = (numsToIndex[sum - *iter]);
			res[1] = ((int)(iter - nums.begin()));//(int)和-begin()为了严谨
			return res;
		}
		numsToIndex[*iter] = (int)(iter - nums.begin());//当前节点加入哈希表
		//numsToIndex[sum - *iter] = (int)(iter - nums.begin());//构建键为sum-num[i]的哈希表
	}
}

//找出数组中最长的连续的元素序列
struct Bound{
	int low;
	int high;
	Bound(int l = 0, int h = 0){ low = l; high = h; }
};

int lengthOfLongestConsecutiveSequence(vector<int> &nums)
{
	int local;
	int low, high;
	int maxLength = 0;
	unordered_map<int, Bound> umap;
	for (int i = 0; i < nums.size(); i++)
	{
		if (umap.count(nums[i]))
			continue;
		local = nums[i];
		low = high = local;

		//计算新的最值
		if (umap.count(local - 1))
		{
			low = umap[local - 1].low;
		}
		if (umap.count(local + 1))
		{
			high = umap[local + 1].high;
		}
		//统一最值
		umap[low].high = umap[local].high = high;
		umap[high].low = umap[local].low = low;

		if ((high - low + 1) > maxLength)
		{
			maxLength = high - low + 1;
		}
	}
	return maxLength;
}

int main()
{
	vector<int> nums = { 1, 2, 3, 4, 5, 6 };
	int sum = 10;
	vector<int> res = addsToSum(nums, 10);
	cout << "和为" << sum << "的一对元素脚标为:" << res[0] << " " << res[1] << endl;

	vector<int> nums1 = { 3, 8, 34, 7, 31, 9, 5, 12, 6, 6, 23 };
	int maxLength = lengthOfLongestConsecutiveSequence(nums1);
	cout << "最大有序序列长度是:" << maxLength << endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值