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

来源:互联网 发布:windows 安装xcode教程 编辑:程序博客网 时间:2024/06/14 02:31

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

在编程中,当处理当期节点的内容需要依赖之前的部分结果时,可以使用哈希表记录之前的结果,本质类似于动态规划(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;}


原创粉丝点击