Two Sum

问题描述: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].

1. 暴力穷举

思路:开始的时候我打算用python的itertools库中的combinations函数来直接生成所有的组合,然后再判断是否等于target,如果等于返回这组数,然后再用list的index函数返回i坐标。但这个思路出现了一个问题,给定的list中出现重复的元素时,用index返回坐标会只返回前面的坐标。于是我打算用暴力穷举来实现这个算法。

代码:

 class Solution { public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> a;
            for (int i = 0; i < nums.size(); i++) {
                for (int j = i + 1; j < nums.size(); j++) {
                    if (nums[j] == target - nums[i]) {
                        a.push_back(i);
                        a.push_back(j);
                        return a;
                    }
                }
            }
        } }; 

复杂度:当然这里使用了两层循环,时间复杂度是 O(n2) ,空间复杂度是 O(1)

2. map

思路:为了减少时间复杂度,我采用map来存储value和index,这样一来,我们就可以在 O(1) 内找到index了。当然把元素放到map中会耗费我们 O(n) 的复杂度。

代码:

#include<map>
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> a;
        vector<int> result;
        for(int i = 0 ; i < nums.size() ; i++)
        {
            a[nums[i]] = i;
        }
        for(int i = 0 ; i < nums.size() ; i++)
        {
            int b = target - nums[i];
            map<int,int>::iterator it;
            it = a.find(b);
            if(a.count(b) && it->second != i)
            {
                result.push_back(i);
                result.push_back(it->second);
                return result;
            }
        }
    }
};

复杂度:时间复杂度 O(n) ,空间复杂度 O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值