[leetcode]167. Two Sum II - Input array is sorted

原创 2016年08月28日 16:20:41

解法一:没有用到已排序属性

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        
        map<int,int>m;
        map<int,int>::iterator iter;
        
        vector<int>ret;
        
        for(int i=0;i<numbers.size();i++)
        {
            iter=m.find(target-numbers[i]);
            if(iter!=m.end())
            {
                ret.push_back(iter->second+1);
                ret.push_back(i+1);
            }
            m.insert(pair<int,int>(numbers[i],i));
        }
        return ret;
    }
};

解法二

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        
        vector<int>ret;
        
        int l=0;
        int r=numbers.size()-1;
        
        while(l<r)
        {
            if(numbers[l]+numbers[r]==target)
            {
                ret.push_back(l+1);
                ret.push_back(r+1);
                return ret;
            }
            if(numbers[l]+numbers[r]>target)
            {
                r--;
            }
            else
            {
                l++;
            }
        }
        return ret;
    }
};




版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[leetcode] 167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascend...

[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...

LeetCode笔记:167. Two Sum II - Input array is sorted

在有序数组中找出相加得到目标数字的两个数的索引

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 t...

LeetCode167.Two Sum II - Input array is sorted题解

1. 题目描述Given an array of integers that is already sorted in ascending order, find two numbers suc...

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 ...

【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 the...

[leetcode] 167. Two Sum II - Input array is sorted

[leetcode] 167. Two Sum II - Input array is sorted

【leetcode】167. Two Sum II - Input array is sorted

Difficulty:Medium Given an array of integers that is already sorted in ascending order, find two ...

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 th...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)