前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关关的刷题日记14——Leetcode 167. Two Sum II - Input array is sorted

关关的刷题日记14——Leetcode 167. Two Sum II - Input array is sorted

作者头像
WZEARW
发布2018-04-09 11:22:21
6390
发布2018-04-09 11:22:21
举报
文章被收录于专栏:专知专知

关小刷刷题14 – Leetcode 167. Two Sum II - Input array is sorted

题目

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. 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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

这题与two sum的区别是,数组是按照从小到大的顺序排好序的,参考一下刷题日记11中的两种做法。

方法1

方法1:双重指针,时间复杂度O(n)。对于排好序的数组这种方法非常好!

代码语言:javascript
复制
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int i=0, j=numbers.size()-1;
        vector<int>output(2,0);
        while(true)
        {
            int sum=numbers[i]+numbers[j];
            if(sum>target)
                j--;
            else if(sum<target)
                i++;
            else
            {
                output[0]=i+1;
                output[1]=j+1;
                break;
            }
        }
        return output;
    }
};

方法2

方法2:哈希表,时间复杂度O(n).

代码语言:javascript
复制
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int>output(2,0);
        hash_map<int, int>m;
        for(int i=0; i<numbers.size(); i++)
        {
            if(m.find(target-x)!=m.end())
                m[x]=i+1;
            else
            {
                output[0]=min(m[x], m[target-x]);
                output[1]=max(m[x], m[target-x]);
                break;
            }
        }
        return output;
    }
};

只有非常努力,才能看起来毫不费力,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-10-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关小刷刷题14 – Leetcode 167. Two Sum II - Input array is sorted
    • 题目
      • 方法1
        • 方法2
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档