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. 看动画学算法之:linkedList

    目录 简介 linkedList的构建 linkedList的操作 头部插入 尾部插入 中间插入 删除节点 简介 linkedList应该是一种非常非常简单的数据结构了.节点一个一个的连接起来,就成了 ...

  2. 【原创】Linux虚拟化KVM-Qemu分析(四)之CPU虚拟化(2)

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: KVM版本:5.9 ...

  3. 许嵩新歌《放肆》发布 && 递归 + Stream+Lambda相遇成树

    一.<放肆>如约而至 今早5:00在迷迷糊糊中醒来,打开手机一看,许嵩又发新歌了,名字叫做<放肆>,澎湃的旋律,依旧古典高雅的用词,这个大男孩,已经不像12年那时候发些伤感非主 ...

  4. PowerShell 语法

    PowerShell 之 教程 PowerShell 中变量.函数命名等不区分大小写,但字符串区分大小写 powershell 脚本文件 扩展名为 .ps1 调用操作符 & + Cmd Cmd ...

  5. 你想了解的《javaScript语言精粹》(三)

    # javaScript语言精粹  # 第三章 对象 - javaScript 数据类型     1. 基础数据类型         Number String Boolean Undefined N ...

  6. Jenkins+pytest+Allure搭建自动化测试

    持续集成(CONTINUOUS INTEGRATION) 在CI环境中,开发人员将会频繁地向主干提交代码.这些新提交的代码在最终合并到主干前,需要经过编译和自动化测试流进行验证. 持续交付(CONTI ...

  7. 【C语言/C++编程学习笔记】你的第一个Windows程序!高级操作~

    什么是windows编程?了解到Windows API 编程.Windows编程.Windows SDK 编程是一个概念.今天我们运用C语言来实现你的第一个真正的Windows程序. windows. ...

  8. CVE-2010-2883-CoolType.dll缓冲区溢出漏洞分析

    前言 此漏洞是根据泉哥的<漏洞战争>来学习分析的,网上已有大量分析文章在此只是做一个独立的分析记录. 复现环境 操作系统 -> Windows XP Sp3 软件版本 -> A ...

  9. js 判断客户端 和 asp.net/C#判断客户端类型

    1.js 判断客户端 <script language="JavaScript"> <!-- onload = function browserRedirect( ...

  10. 圆形进度条的模仿3-DrawArc,DrawCircle,DrawText,自定义属性实例讲解

    前面两篇中已经讲过如何使用drawARC,等,画其他的图形的方法的使用也是一样的,只是参数不同, 同时也讲了如何通过xml进行自定义属性,接下来这篇便是通过实例讲解如何实地应用起来, 效果如下,点击开 ...