LeetCode #1:Two Sum(简单题)

原题

原题地址
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].

翻译

给定一个数组,返回两个数字的下标索引,使它们相加到特定值。
你可以认为输入的每个测试用例只有一个特定解且数组中没有值相同的元素。
示例:
数组 nums=[2, 7, 11, 15],目标target=9,
因为nums[0] + nums[1] = 2 + 7 = 9,
返回[0,1].

分析

直接用BF(Brute Force)暴力求解就是通过两层循环嵌套完成,时间复杂度O(n2),会超时,不是一个很好的方法,此处不再赘述。
第二种方法就是以时间换空间,把数组存到一个map里面,map的key为数组的值,map的value为数组的下标。这样只需要遍历原数组,查看a=target-nums[i]的值在不在map的下标中,如果存在且map[a]与i不相等,则这两个值就是需要返回的下标。
时间复杂度O(n),空间复杂度O(n)。
代码如下:

代码(C++)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> Myset;
        vector<int> results;
        for (auto tmp = nums.begin(); tmp<nums.end(); tmp++) Myset[*tmp] = tmp - nums.begin();
        for (auto tmp = Myset.begin(); tmp != Myset.end(); tmp++) cout << (*tmp).first << " "<< (*tmp).second<<endl;

        for (auto tmp = nums.begin(); tmp < nums.end(); tmp++)
        {
            if (Myset.find(target - *tmp) != Myset.end()&& (*Myset.find(target - *tmp)).second!=(tmp - nums.begin()))
            {
                results.push_back(tmp - nums.begin());
                results.push_back(Myset[target - *tmp]);
                break;
            }
        }
        return results;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值