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

题目描述

给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:

给出的数组为 {2, 7, 11, 15},目标值为9
输出 ndex1=1, index2=2

示例1

输入

[3,2,4],6

输出

[2,3]
//方法一 暴力

//方法二 C++版本的两遍哈希表(官方题解)
/*
通过以空间换取速度的方式,我们可以将查找时间从 O(n) 降低到 O(1)。
C++版本的哈希表算法采用unordered_map。
*/
vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> ans;
    unordered_map<int,int> tmpmap;
    int length = nums.size();
    for(int i = 0;i < length;i++){
        tmpmap[nums[i]] = i;
    }
    for (int i = 0; i < length; i++){
        if(tmpmap.count(target - nums[i]) != 0 && tmpmap[target - nums[i]] != i){  
        //使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。
            ans.push_back(i);
            ans.push_back(tmpmap[target - nums[i]]);
            break;
        }
    }
    return ans;
}

//方法三 C++版本的一遍哈希表(官方题解)
/*
事实证明,我们可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查
表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
*/
vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> ans;
    unordered_map<int,int> tmpmap;
    int length = nums.size();
    for (int i = 0; i < length; i++){
        if(tmpmap.count(nums[i]) != 0){
            ans.push_back(tmpmap[nums[i]]);
            ans.push_back(i);
            break;
        }
        tmpmap[target - nums[i]] = i;
    }
    return ans;
}
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        cache = {}
        for index,num in enumerate(nums):
            another_num = target-num
            if another_num in cache:
                return [cache[another_num],index]
            cache[num]=index
        return None

leetcode148two-sum的更多相关文章

  1. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  2. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  3. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  4. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  5. BZOJ 3944 Sum

    题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [LeetCode] Partition Equal Subset Sum 相同子集和分割

    Given a non-empty array containing only positive integers, find if the array can be partitioned into ...

  8. [LeetCode] Split Array Largest Sum 分割数组的最大值

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  9. [LeetCode] Sum of Left Leaves 左子叶之和

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

  10. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

随机推荐

  1. 插头 dp

    插头dp 洛谷 黑题板子? P5056 给出n×m的方格,有些格子不能铺线,其它格子必须铺,形成一个闭合回路.问有多少种铺法? 1.轮廓线 简单地说,轮廓线就是已决策格子和未决策格子的分界线: 2,插 ...

  2. 手写一个类SpringBoot的HTTP框架:几十行代码基于Netty搭建一个 HTTP Server

    本文已经收录进 : https://github.com/Snailclimb/netty-practical-tutorial (Netty 从入门到实战:手写 HTTP Server+RPC 框架 ...

  3. shell脚本中,关于if,以及条件判断

    #!/bin/sh SYSTEM=`uname -s` #获取操作系统类型 if [ $SYSTEM = "Linux" ] ; then #如果是linux的话打印linux字符 ...

  4. Linux系统如何在离线环境或内网环境安装部署Docker服务和其他服务

    如何在离线环境或纯内网环境的Linux机器上安装部署Docker服务或其他服务.本次我们以Docker服务和Ansible服务为例. 获取指定服务的所有rpm包 保证要获取rpm包的机器能够上网. 本 ...

  5. Vuejs上传

    下载 Vuejs上传Vuejs上传 多部分上传Vue组件. 上传器可以选择上传多部分的文件. 这是关于最大的上传尺寸,允许你上传大文件. 如果prop multiple为真,文件列表将在选择文件时呈现 ...

  6. XML流操作

    /// <summary>         /// 保存XML为指定格式         /// </summary>         /// <param name=& ...

  7. OpenCV计算机视觉学习(4)——图像平滑处理(均值滤波,高斯滤波,中值滤波,双边滤波)

    如果需要处理的原图及代码,请移步小编的GitHub地址 传送门:请点击我 如果点击有误:https://github.com/LeBron-Jian/ComputerVisionPractice &q ...

  8. 多测师讲解pthon_re模块_高级讲师肖sir

    #import re   一.我们就re模块(也叫正则模块)介绍: 实现一个编译查找,一般在日志处理或者文件处理时用的比较多 正则表达式主要用于模式匹配和替换工作.     预定义字符集匹配: \d: ...

  9. day58 Pyhton 框架Django 01

    内容回顾 python基础    网路编程    并发编程    数据库    前端     osi7层           tcp/ip 5层模型    应用层    表示层             ...

  10. 【C语言C++编程入门】——程序结构:构思!

    学习编程语言的最好方法是编写程序.一般来说,初学者编写的第一个程序是一个名为"Hello World"的程序,它简单地将"Hello World"打印到你的电脑 ...