LeetCode题解——1TwoSum

来源:互联网 发布:淘宝仓库管理系统 编辑:程序博客网 时间:2024/05/24 16:13

题目:

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

0 0
原创粉丝点击