美文网首页程序员
Leetcode - Two Sum II - Input ar

Leetcode - Two Sum II - Input ar

作者: 哈比猪 | 来源:发表于2016-10-13 10:56 被阅读0次

    题目链接

    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.
    Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

    解题思路

    TODO (稍后补充)

    解答代码

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

    相关文章

      网友评论

        本文标题:Leetcode - Two Sum II - Input ar

        本文链接:https://www.haomeiwen.com/subject/acswyttx.html