[array] leetCode-1-Two Sum-Easy

leetCode-1-Two Sum-Easy

descrition

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

example

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解析

  • 方法 1 : 2 重循环去检查两个数的和是否等于 target。时间复杂度-O(n^2),空间复杂度 O(1)
  • 方法 2 : 以空间换时间,使用 hash 表存储已访问过的数,实际上是省去了方法 1 中内层循环的查找时间,时间复杂度 O(n),空间复杂度 O(n)

注意:题目的假设,输入保证有且只有一个解;返回的是下标

code


#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>

using namespace std;

class Solution{
public:
	vector<int> twoSum(vector<int>& nums, int target){
		return twoSumByMap(nums, target);
	}

	// time-O(n), space-O(n)
	vector<int> twoSumByMap(vector<int>& nums, int target){
		vector<int> ans;
		unordered_map<int, int> hash; // <num, index>
		for(int i=0; i<nums.size(); i++){
			int another = target - nums[i];
			if(hash.find(another) != hash.end()){
				// then complexity of unordered_map.find() is 
				// average case: constant
				// worst case: linear in container size
				ans.push_back(hash[another]);
				ans.push_back(i);
				return ans;
			}
			hash[nums[i]] = i;
		}

		return ans;
	}

};

int main()
{
	freopen("in.txt", "r", stdin);
	vector<int> nums;
	int target;
	int cur;
	cin >> target;
	while(cin >> cur){
		nums.push_back(cur);
	}
	vector<int> ans = Solution().twoSum(nums, target);
	if(!ans.empty())
		cout << ans[0] << " " << ans[1] << endl;
	else
		cout << "no answer" << endl;

	fclose(stdin);

	return 0;
}

原文地址:https://www.cnblogs.com/fanling999/p/7817267.html