前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode系列】167. 两数之和 II - 输入有序数组

【leetcode系列】167. 两数之和 II - 输入有序数组

作者头像
lucifer210
发布2019-08-16 10:41:48
3410
发布2019-08-16 10:41:48
举报
文章被收录于专栏:脑洞前端脑洞前端

题目描述

这是leetcode头号题目 two sum的第二个版本,难度简单。

代码语言:javascript
复制
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

说明:

返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

由于题目没有对空间复杂度有求,用一个hashmap 存储已经访问过的数字即可。

假如题目空间复杂度有要求,由于数组是有序的,只需要双指针即可。一个left指针,一个right指针, 如果left + right 值 大于target 则 right左移动, 否则left右移,代码比较简单, 不贴了。

如果数组无序,需要先排序(从这里也可以看出排序是多么重要的操作)

关键点解析

代码

代码语言:javascript
复制
/*
 * @lc app=leetcode id=167 lang=javascript
 *
 * [167] Two Sum II - Input array is sorted
 *
 * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
 *
 * algorithms
 * Easy (49.46%)
 * Total Accepted:    221.8K
 * Total Submissions: 447K
 * Testcase Example:  '[2,7,11,15]\n9'
 *
 * Given an array of integers that is already sorted in ascending order, 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.
 *
 * Note:
 *
 *
 * Your returned answers (both index1 and index2) are not zero-based.
 * You may assume that each input would have exactly one solution and you may
 * not use the same element twice.
 *
 *
 * Example:
 *
 *
 * Input: numbers = [2,7,11,15], target = 9
 * Output: [1,2]
 * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
 *
 */
/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(numbers, target) {
    const visited = {} // 记录出现的数字, 空间复杂度N

    for (let index = 0; index < numbers.length; index++) {
        const element = numbers[index];
        if (visited[target - element] !== void 0) {
            return [visited[target - element], index + 1]
        }
        visited[element] = index + 1;   
    }
    return [];
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 脑洞前端 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路
  • 关键点解析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档