Leetcode Problem 1: Two sum

Description

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目的意思是:要在一个数组里面找出两个数,使得他们相加的和等于给定的数,输出两个数的在数组里面对应的索引。

Solution

最基本的思路是穷竭搜索(暴搜),两重循环,时间复杂度O(n^2);这个方法会造成Time Limited Exceed,测试用例是个很大的一维数组。

更好的办法是使用map: 可以达到O(n)的时间复杂度。记忆化搜索,遍历数组时,先在map里面查询target-num(和减去当前的数字),如果没有找到,则将当前数字(做为key)和对应的数组索引(做为value)保存在map中,如果找到了,则直接输出。

这里选择STL里面的unordered_map作为map数据结构的实现。

Code

/**
 * Leetcode problem list 1: two sum.
 * Use map algorithm(stl). 
 *
 * hellfire(asyncloading#163.com)
 * Feb 15th, 2016
 */
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;

class Solution {
  public:
    vector<int> twoSum(vector<int>& nums, int target) {
      vector<int> output(2);
      unordered_map<int, int> umap;      

      for (int i = 0; i < nums.size(); i ++)
      {
        if (umap.find(target - nums[i]) != umap.end())
        {
          output[0] = umap[target - nums[i]];
          output[1] = i;
        }
        else
        {
          umap.insert(make_pair(nums[i], i));
        }  
      }
      return output; 
    }
};

int main(int argc, char **argv)
{
  Solution s;
  int arr[] = {2, 7, 11, 15};
  int target = 13;
  vector<int> nums(arr, arr + 3);
  vector<int> output = s.twoSum(nums, target);
  cout << output[0] << output[1] << endl;
}

源代码对应的Github地址: https://github.com/oj-problem/leetcode/blob/master/solution1.cpp

备注

c++语法:不能直接将数组赋值给vector容器,可以采用下面的方式。

  int arr[] = {2, 7, 11, 15};
  vector<int> nums(arr, arr + 3);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值