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 };
  • 相关阅读:
    python如何打开一个大文件?
    python中的多进程与多线程(二)
    python中的多进程与多线程(一)
    python中的深拷贝与浅拷贝
    2018 pycharm最近激活码
    python中的新式类与旧式类
    用python优雅打开文件及上下文管理协议
    解决Mac上安装mysqlclient的错误
    用python实现一个简单的服务器
    高阶函数
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4493963.html
Copyright © 2011-2022 走看看