LeetCode 167.Two Sum II 解题报告

来源:互联网 发布:人工智能的利弊英文 编辑:程序博客网 时间:2024/06/08 15:00

LeetCode 167.Two Sum II 解题报告

题目描述

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


限制条件

没有明确给出。


解题思路

题目说了数组是排序的,这样难度就降低了。由于数组是升序排列,所以两个数之和sum为目标值target,则肯定是小的数在前,大的数在后,这样明显是双指针的问题。
建立一个指针指向数组第一个元素,建立另一个指针指向数组最后一个元素,为了方便,暂时称为左右指针,通过将它们的和与目标值比较,有三种情况:

  • sum>target,说明右指针指向的元素过大,所以向左移动右指针。
  • sum<target,说明左指针指向的元素过小,所以向右移动左指针。
  • sum=target,找到了和为target的两个数的索引,返回这两个索引。
    通过一个循环,重复上述的情况检查,循环结束的条件是左指针指向的位置不再小于右指针指向的位置。

代码

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

总结

双指针的问题还是比较容易处理的,关键是确定好指针更新的条件,以及结束移动指针的条件。
今天又遇到了一道双指针的题目,同样地当把双指针的题目都做完了会写个小小的总结,当做复习整理。继续不怀好意地盯着下一个坑,嘻嘻嘻~~

0 0
原创粉丝点击