zoukankan      html  css  js  c++  java
  • Two Sum 分类: Leetcode(线性表) 2015-02-04 10:05 57人阅读 评论(0) 收藏

    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.

    说好的hash呢

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            unordered_map<int, int> mapping;
            vector<int> vec;
            int i;
            for(i = 0; i < numbers.size(); i++){
                mapping[numbers[i]] = i;
            }
            
            int gap;
            
            for(i = 0 ; i< numbers.size(); i++){
                gap = target - numbers[i];
                if( mapping.find(gap) != mapping.end() && mapping[gap] >i ){
                    vec.push_back(i+1);
                    vec.push_back(mapping[gap]+1);
                }
            }
            return vec;
            
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Serverless 动态博客开发趟“坑”记
    tsv与csv文件
    zypper
    source、sh、./三种执行方式对脚本变量的影响
    linux nm
    ldconfig
    cpio
    License简介
    rpm之spec文件
    使用rpmbuild制作rpm包
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656958.html
Copyright © 2011-2022 走看看