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

    分析:在一个数组中找到两个数相加和为给定数字的下标。要注意的是下标从1开始,同时可以假设每组输入存在且只存在一组解。

    可以考虑用map存储 值-下标对。特别要注意的是要排除找到自身的情况。比如v = {3, 2, 4}, target = 6. 按照我们的思路绝对会输出[1, 1],因为对3进行找小伙伴的操作时,会find到3。为避免该情况,加入一个判断hmap[target - nums[j]] != j(line 8)

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         map<int, int> hmap;
     5         vector<int> result;
     6         for(int i = 0; i < nums.size(); i++) hmap[nums[i]] = i;
     7         for(int j = 0; j < nums.size(); j++){
     8             if(hmap.find(target - nums[j]) != hmap.end() && hmap[target - nums[j]] != j){
     9                 result.push_back(j + 1);
    10                 result.push_back(hmap[target - nums[j]] + 1);
    11                 return result;
    12             }
    13         }
    14     }
    15 };
  • 相关阅读:
    (转)CentOS 6.5下Redis安装详细步骤
    (转)FastDFS_v5.05安装配置
    Mybatis 动态获取字段值(不需要创建javabean)
    Apache+tomcat集群配置
    Get Started and Make Progress in Machine Learning
    NLTK 模块不完全介绍
    python __future__
    python __init__.py和__all__
    自然语言处理
    Python搜索路径
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4493963.html
Copyright © 2011-2022 走看看