• 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 };

  • 相关阅读:
    Code-Helper:RegexHelper.cs
    Code-Convert:Image to base64
    un-System.Reflection.IReflect.cs
    System.Reflection.AssemblyName.cs
    System.Reflection.ConstructorInfo.cs
    System.Attribute.cs
    ERROR<53761>
    /dev/null 文件
    linux telnet服务安装与配置
    linux定时任务2-at命令
  • 原文地址:https://www.cnblogs.com/riden/p/4564484.html
Copyright © 2020-2023  润新知