【第22期】观点:IT 行业加班,到底有没有价值?

[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;
    }
};




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

相关文章推荐

167.[LeetCode]Two SumII

这道题要是用哈希的话,时间复杂度也是 O(n),但是也可以不适用额外空间达到O(n),也是我们经常适用的方法,双指针法// 这个是金典的 两数和 的问题,如何在o(n)的时间复杂度内完成呢? publ...

LeetCode 167. Two Sum II - Input array is sorted(两数和)

原题网址:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ Given an array of integers th...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

leetcode 167. Two Sum II - Input array is sorted

public class Solution { public int[] twoSum(int[] numbers, int target) { int front = 0, ...

167. Two Sum II - Input array is sorted

class Solution { public: vector twoSum(vector& numbers, int target) { int i=0; i...

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

题目链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description Given an array o...

【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 Given an array of integers that is already sorted in ascending order, f...

[LeetCode]154.Find Minimum in Rotated Sorted Array II

【题目】 <blockquote style="padding: 10px 20px; margin: 0px 0px 20px; font-size: 17.5px; border-left-width: 5px; border-left-style: solid; bord...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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