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 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.

Note:

  • 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.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1

中文大意:

给定一个已按升序排序的整数数组,找到两个数字,使它们相加得到一个特定的目标数字。函数two和应该返回两个数字的指标,使它们相加得到目标值,其中index1必须小于index2。

注记:您返回的答案(index1和index2)不是基于零的。您可以假设每个输入都只有一个解决方案,并且可能不会两次使用相同的元素。

解题思路:

一个数组,取两个值相加得到target,由于这个数组它的顺序是有序的,所以分别去前面的值与后面的值进行相加,当得到result结果时,我们可以返回一个result数组值,即返回最后的结果

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        // 最后的返回的数组,记录结果数组由那两个位置的值进行相加的到
        int[] result = new int[2];
        // 前向的标记
        int count1 = 0;
        // 后向的标记
        int count2 = numbers.length - 1;
        // 依次遍历数组
        while (count1 < count2) {
            // 得到result时,返回两个结果位置
            if (numbers[count1] + numbers[count2] == target) {
                result[0] = count1 + 1;
                result[1] = count2 + 1;
                break;
            }
            // 结果大于target时,将后面的count2向前移
            else if (numbers[count1] + numbers[count2] > target) {
                count2--;
            }
            // 结果小于target时,将前面的count1向后移
            else {
                count1++;
            }
        }
        return result;
    }
}

  

  

posted @   leagueandlegends  阅读(192)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示