zoukankan      html  css  js  c++  java
  • 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.

    Example:

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

     UPDATE (2016/2/13):

    The return format had been changed to zero-based indices. Please read the above updated description carefully.

     Subscribe to see which companies asked this question

     1 #include<iostream>
     2 #include<map>
     3 #include<vector>
     4 using namespace std;
     5 class Solution {
     6 public:
     7     vector<int> twoSum(vector<int>& nums, int target) {
     8         vector<int> res;
     9         map<int,int> hashmap;
    10         int find_num;
    11         for(int i=0;i<nums.size();i++)
    12         {
    13             find_num=target-nums[i];
    14             map<int,int>::iterator it=hashmap.find(find_num);
    15             if(it!=hashmap.end())
    16             {
    17                 res.push_back(i);
    18                 res.push_back(it->second);
    19                 return res;
    20             }
    21             hashmap[nums[i]]=i;
    22         }
    23     }
    24 };
  • 相关阅读:
    codevs1004 四子连棋
    codevs1009 产生数
    NOIP2014 寻找道路
    Tyvj1139 向远方奔跑(APIO 2009 抢掠计划)
    随机算法
    线性基
    线性基入门
    线性基 + 并查集
    欧拉公式 (平面)
    卡特兰数 + 大数
  • 原文地址:https://www.cnblogs.com/mrlsx/p/5431187.html
Copyright © 2011-2022 走看看