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. c语言 static的用法

    static在c里面可以用来修饰变量,也可以用来修饰函数.先看用来修饰变量的时候.变量在c里面可分为存在全局数据区.栈和堆里.其实我们平时所说的堆栈是栈而不是堆,不要弄混.int a ;int mai ...

  2. 【题解】CF413C Jeopardy!

    \(\color{blue}{Link}\) \(\text{Solution:}\) 首先,显然的策略是把一定不能翻倍的先加进来.继续考虑下一步操作. 考虑\(x,y\)两个可以翻倍的物品,且\(a ...

  3. Ubuntu18.04修改apt-get源

    1)备份源文件: sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak 2)查看版本信息 如是Linux Mint等Ubuntu衍生版,执行: ...

  4. 达梦产品技术支持培训-day6-DM性能诊断与优化

    (本文只作为个人随笔用途,非官方文档,请勿作他用,谢谢) 1.DM8查询优化基本思路 1.1 操作系统性能诊断 linux常用系统监控命令 使用 top 命令查看cpu使用率 使用 iostat 命令 ...

  5. 极客 Play 玩 Terminal——GitHub 热点速览 Vol.40

    作者:HelloGitHub-小鱼干 多少人以为暗黑的终端便是一名程序员的工作台,其实上,终端可以不只是一个输入 command 的界面,也可以是本周特推 kb 一样,面向极客的极简命令行知识库管理器 ...

  6. 《New Horizon College English》 (Third Edition) -长篇阅读(Skmming and Scanning)

    <New Horizon College English>(Third Edition) <新视野大学英语>(第三版) 长篇阅读(Skmming and Scanning) 总 ...

  7. C# excel文件导入导出

    欢迎关注微信公众号 C#编程大全 这里有更多入门级实例帮你快速成长 在C#交流群里,看到很多小伙伴在excel数据导入导出到C#界面上存在疑惑,所以今天专门做了这个主题,希望大家有所收获! 环境:wi ...

  8. LVS+keepalive

    LVS+keepalive 什么是keepalive Keepalived是Linux下一个轻量级别的高可用解决方案.高可用(High Avalilability,HA),其实两种不同的含义:广义来讲 ...

  9. springboot1.5和jpa利用HikariCP实现多数据源的使用

    背景 现在已有一个完整的项目,需要引入一个新的数据源,其实也就是分一些请求到从库上去 技术栈 springboot1.5 (哎,升不动啊) 思路 两个数据源,其中一个设置为主数据源 两个事物管理器,其 ...

  10. 利用HDFS实现ElasticSearch7.2容灾方案

    利用HDFS实现ElasticSearch7.2容灾方案 目录 利用HDFS实现ElasticSearch7.2容灾方案 前言 快照版本兼容 备份集群 HDFS文件系统 软件下载 JDK环境 配置系统 ...