LeetCode 167. Two Sum II

来源:互联网 发布:网络b类违规是什么意思 编辑:程序博客网 时间:2024/05/16 15:44

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=9
Output: index1=1, index2=2

三、解题思路

  • 最简单的方法,遍历数组,找到一个nums[i] 就去遍历剩下的看有没有和为target的,有就返回。时间复杂度是o(n2)
class Solution {public:    int hasExpectNum(const vector<int>& numbers, int start, int expect)    {        int n = numbers.size();        for (int i = start; i < n; ++i) {            if(numbers[i] == expect) return i;            if(numbers[i] > expect) return -1;        }        return -1;    }    vector<int> twoSum(vector<int>& numbers, int target) {        int n = numbers.size();        for (int i = 0; i < n; ++i) {            int expect = target - numbers[i];            int index = hasExpectNum(numbers, i + 1, expect);            if(index != -1){                return vector<int>{i+1, index+1};            }        }    }};
原创粉丝点击