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].

根据题目的意思就是要在一个数组中找出两个元素之和为给定数的值

思路一:
首先想到就是最简单最暴力的两个for循环,固定一个数,再去寻找数组中的其他数相加与给定数进行比较。这种方法的时间复杂度为O(nlogn).

思路二:
可以通过哈希表的索引值更快的查找另一个差值,也就是判断 target-nums[i] 是否在哈希表中,此方法时间复杂度为O(n),空间复杂度是O(1)

//
// Created by will on 2017/12/14.
//


/*
 *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.
 */

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


using namespace std;
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        /*
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = i+1; j < nums.size(); ++j) {
                if(nums[i]+nums[j] == target){
                    vector<int> sum ={i,j};
                    return sum;
                }
            }
        }
         */

        unordered_map<int, int> map;
        vector<int> resoult;

        for (int i = 0; i < nums.size(); i++) {
            int tofind = target - nums[i];
            if (map.count(tofind)){
                resoult.push_back(map[tofind]);
                resoult.push_back(i);
                break;
            }

            //number was not found. Put it in the map.
            map[nums[i]] = i;
        }

        return resoult;

    }
};


int main(){

    vector<int> nums = {2, 7, 11, 15};
    Solution s;
    vector<int> sum = s.twoSum(nums,9);

    cout<<sum[0]<<"  "<<sum[1]<<endl;
    return 0;

}

这道题刚开始我一直在看为什么一个未赋值的哈希表中查找数组中的值,想了半天也没想出来,知道看到了后面的map[nums[i]] = i,因为第一次的查找肯定是没有值的,随后会将数组中的值放入到哈希表中。

而且这道题的难点在于不容易想到利用哈希表来解决问题,但是如果留意到You may assume that each input would have exactly one solution 就不难想到哈希表中的唯一值的特点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值