zoukankan      html  css  js  c++  java
  • Two Sum

    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

    class Solution {
    public:
        vector<int> twoSum(const vector<int> &numbers, int target) {
            map<int, int> m;
            vector<int> result;
            for(int i=0; i<numbers.size(); i++){
                if (m.find(numbers[i])==m.end() ) { 
                    m[target - numbers[i]] = i; 
                }else { 
                    result.push_back(m[numbers[i]]+1);
                    result.push_back(i+1);
                    break;
                }
            }
            return result;
        }
    };
  • 相关阅读:
    sed命令
    python常用库
    python标准库
    从 Python 打包到 CLI 工具
    pip
    python包自我理解
    docker常用命令
    chattr命令
    xmss
    live2d-widget.js
  • 原文地址:https://www.cnblogs.com/chybot/p/4481658.html
Copyright © 2011-2022 走看看