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. 51单片机I2C总线

    I2C总线是飞利浦公司推出的一种串行总线,所有器件共用两根信号线,实现数据的传输. 总线接口接了上拉电阻,默认为高电平,所以就可以用"当低电平出现"来标记出一种起始信号.我个人把它 ...

  2. Excel-VLOOKUP函数跨表匹配查找①

    问题场景 对表中的员工进行测评总结,从所有员工考核明细表中匹配这些参与测评的员工的得分和相关信息: 场景一 从所有员工明细表中匹配需要参与测评的员工相关信息. 建了两个sheet页,考核员工表和全员考 ...

  3. javaOOP9.17刷题

    今天在吃晚饭和朋友们聊天的时候,一个已经在自己写java全栈项目并且准备面试的同学说要我好好学习OOP这部分,他现在写代码写面试题,发现自己都忘了基类派生类调用构造函数时候的顺序是什么样的巴拉巴拉,说 ...

  4. Java 将Html转为PDF(二)

    前面介绍了如何通过插件的方式将Html文件转为PDF,该方法需要使用Spire.PDF for Java 3.6.6或者之后的新版本,可根据自己的系统选择不同插件来实现转换.本文提供另外一种转换方法, ...

  5. ansible-playbook-roles基本使用

    1. ansible-角色-roles基本使用  1.1) 创建roles目录结构 1 [root@test-1 ansible]# mkdir -p /ansible/roles/{common,n ...

  6. iOS企业重签名管理软件之风车签名

    这是一款在Mac平台下安全可控的iOS签名管理软件,旨在对签名后的APP能够完全控制,包括APP的开启或禁用.设置到期时间锁.注入第三方动态库文件.设置安装限量.修改APP名称和自定义Bundle I ...

  7. 开始接触flex

    flex框架使用的是.mxml后缀的文件,可以在Eclipse导入flex开发的插件.代码写完之后需要进行编译成为.swf文件成功之后才可以正常运行.现在刚开始接触金融的项目,需求什么的还有很多不是理 ...

  8. IGBT以及MOSFET驱动参数的计算方法

  9. C++11随机数库

    random随机数库 C++11引入了新的随机数生成机制,那就是<random>随机数库,支持多种伪随机数生成算法,多种连续和离散随机数分布算法,以及封装了真正的随机数生成引擎random ...

  10. 【树形DP】BZOJ 1131 Sta

    题目内容 给出一个\(N\)个点的树,找出一个点来,以这个点为根的树时,所有点的深度之和最大 输入格式 给出一个数字\(N\),代表有\(N\)个点.\(N \le 1000000\).下面\(N-1 ...