LeetCode题解——1TwoSum
2015-06-27 11:17
190 查看
题目:
Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路:
题目的要求是给定一个数组,找出数组中和为一定值的两个数。也就是给定一定值target,从数组中要找出a+b=target。等式转换一下,我们可以知道,a=target-b。所以我们要做的事情可以翻译为,找到一个数a,满足a与target-a都在数组之中。第一个思路,遍历数组中的某一个数,对于每个数再一次遍历数组中的所有数,找到满足条件的两个数。这个算法的时间复杂度为O(n2),空间复杂度为O(1)。
第二个思路,在前一个算法的基础上降低时间复杂度。我们可以将数组排序,然后定义两个指针,一个指针从左向右,另一个从右向左,遍历直到找到满足条件的两个数。由于排序的最佳时间复杂度为O(nlogn),两个指针的遍历时间复杂度为O(n)。所以总的时间复杂度为O(nlogn)
第三个思路,我希望通过O(n)的时间复杂度完成要求。第一遍O(n)的算法将每个数据a对应的target-a建立查询的数据结构,例如Hash表;第二遍遍历时,查询每个数是否在Hash表中,每次查询时间复杂度为O(1),总的时间复杂度是O(n)。但是Hash表将需要一定的存储空间,为了节省空间,我们可以采用bitmap的方法来最大化的压缩空间复杂度。
// 1TowSum.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <map> #include <unordered_map> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { //map<int,int> nummap; unordered_map<int,int> nummap; vector<int> ans; for(int i=0; i<nums.size(); i++) { if(nummap.find(target-nums[i])!=nummap.end()) { ans.push_back(nummap[target-nums[i]]); ans.push_back(i+1); return ans; } nummap[nums[i]] = i+1; } } }; void main() { vector<int> nums; int N = 4; int a[4]={2,7,11,15}; for(int i=0; i<N ; i++) nums.push_back(a[i]); int target = 18; Solution sl; vector<int> ans = sl.twoSum(nums,target); cout<<ans[0]<<" "<<ans[1]<<endl; }
用map时间为24ms
用unorderedmap时间为16ms
相关文章推荐
- 约炮需谨慎!男子花钱约女网友玩性虐
- 为什么工具类App,都要做一个社区?
- 呼叫保持流程
- 为什么工具类App,都要做一个社区?
- java正则表达式
- 两男一女同睡一床发生关系 事后致五男入狱
- 日语学习之沪江N3基础 20150627 -2
- Java套接字通讯实例...【Pnoker】
- Unity3D发布到虚拟机(WindowsXp虚拟机),使用第一人称鼠标失灵的解决方法
- 成为富翁的6大创业法则
- <context:component-scan base-package=com.xxx.xxx/ >包扫描注解
- shell脚本
- pixelmator处理png图片,处理掉过白的留白。
- List 的赋值问题
- java Jackson 库操作 json 的基本演示
- comparator接口与Comparable接口的区别
- 使用@Controller注解为什么要配置<mvc:annotation-driven />
- 即时通信中的多媒体上传传输与播放
- spring security 4 安全框架学习01
- Testing your Xamarin app on Android device