LeetCode 167.Two Sum II 解题报告

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值