zoukankan      html  css  js  c++  java
  • LeetCode-Two sum

    Question:
    Give 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

    Solution:

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         map<int,int> temp;
     5     vector<int> result;
     6     map<int,int>::iterator iter;
     7     int k;
     8     for(int i=0;i<nums.size();i++)
     9     {
    10         temp[nums[i]]=i+1;
    11     }
    12     for(int j=0;j<nums.size();j++)
    13     {
    14         int x=target-nums[j];
    15         iter=temp.find(x);
    16         if(iter!=temp.end() && iter->second!=j+1)
    17         {
    18             k=iter->second;
    19             result.push_back(min(j+1,k));
    20             result.push_back(max(j+1,k));
    21             break;
    22         }
    23     }
    24     return result;
    25         
    26     }
    27 };

  • 相关阅读:
    5.8
    python运维自动化
    javascript学习(一)
    python学习-1
    A-GPS学习笔记(二) 之SUPL
    A-GPS学习笔记(一)
    CF756D Bacterial Melee
    LG P2495 [SDOI2011]消耗战
    LG P7325 [WC2021] 斐波那契
    LG P7324 [WC2021] 表达式求值
  • 原文地址:https://www.cnblogs.com/riden/p/4564484.html
Copyright © 2011-2022 走看看