zoukankan      html  css  js  c++  java
  • Two Sum

    Description:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    Code:

     1     vector<int> twoSum(vector<int>& nums, int target) {
     2         map<int, int>mNums;
     3         vector<int>result;
     4         
     5         for (int i = 0; i < nums.size(); i++)
     6         {
     7             if ( mNums.count( target-nums[i] ) )
     8             {
     9                 result.push_back( mNums[target-nums[i]]+1 );
    10                 result.push_back( i+1 );
    11                 break;
    12             }
    13             if ( !mNums.count( nums[i] ))
    14                 mNums[nums[i]] = i;
    15         }
    16         return result;
    17     }
  • 相关阅读:
    BigPipe
    HDFS Scribe Integration 【转】
    C++ | class size
    Leetcode | Container With Most Water
    Leetcode | Sqrt(x)
    Network | sk_buff
    JVM, JRE 和JDK
    facebook面试题【转】
    ML | SVM
    ML| EM
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4574953.html
Copyright © 2011-2022 走看看