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


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

  • 相关阅读:
    Mac 删除Openfire
    FMDB使用
    豆瓣restful api 状态和错误码
    豆瓣开放api
    常用文字配色方案
    电商网站参考
    HP后端跨域HEADER头
    PHP统计 图表实现方法
    PHP 全过程教程和测试网
    Ajax技术在购物车中的应用(PHP篇)
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656958.html
Copyright © 2011-2022 走看看