1.twoSum

参考LeetCode网站:

题目: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].
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        
    }
};
LeetCode中代码如下:

vector<int> twoSum(vector<int> &numbers, int target)
{
    //Key is the number and value is its index in the vector.
	unordered_map<int, int> hash;//注意包含unordered_map文件
	vector<int> result;
	for (int i = 0; i < numbers.size(); i++) {
		int numberToFind = target - numbers[i];

            //if numberToFind is found in map, return them
		if (hash.find(numberToFind) != hash.end()) {
			result.push_back(hash[numberToFind]);
			result.push_back(i);			
			return result;
		}

            //number was not found. Put it in the map.
		hash[numbers[i]] = i;
	}
	return result;
}

内部实现机理
  • map: map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素,因此,对于map进行的查找,删除,添加等一系列的操作都相当于是对红黑树进行这样的操作,故红黑树的效率决定了map的效率。
  • unordered_map: unordered_map内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的

问:Does your code take duplicate elements into consideration?
Input such as:

target = 8, items = [2 4 4 7 10]

答:This is not because duplicate numbers, because the solution defines the answer is unique !!! so you do not need to consider duplicates!! It is because that you find the target number in the previous map , so you add element after visit the hash

自定义代码如下,比较简单暂时没有考虑时间复杂度和空间复杂度

vector<int> twoSum1(vector<int> &numbers, int target)
	{
		vector<int> result;
		for (int i = 0; i < numbers.size(); i++)
		{
			for (int k = i + 1; k < numbers.size(); k++)
			{
				if (numbers[i] + numbers[k] == target)
				{
					result.push_back(i);
					result.push_back(k);
					break;
				}
			}
		}
		return result;
	}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值