LeetCode Array Easy 167. Two Sum II - Input array is sorted

 Description

 

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, index2 = 2.

 

题目描述,给定一个已排序的数组,和一个目标值,计算数组中的两个值的和等于目标值时的位置,这里位置不从0开始。

思路: 数组是以排序的,则使用两个指针,分别指向数组的头尾,当两数相加小于目标值是则头指针递增一位,当相加大于目标值值,尾指针递减。

下面是代码,感觉还有优化的地方。先贴出来。

public int[] TwoSum(int[] numbers, int target)
        {
            int[] result = new int[2];
            int lo=0, hi=numbers.Length-1;
            while(lo < hi)
            {
                if (numbers[lo] + numbers[hi] < target) lo++;
                else if (numbers[lo] + numbers[hi] > target) hi--;
                else
                    break;
            }
            result[0] = lo + 1;
            result[1] = hi + 1;
            return result;
        }

 

 

posted @ 2018-08-30 14:27  C_supreme  阅读(141)  评论(0编辑  收藏  举报