1. 程式人生 > >【LeetCode】167. Two Sum II - Input array is sorted

【LeetCode】167. Two Sum II - Input array is sorted

etc 想法 ice ted integer turned abs ascend 要求

原題鏈接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/tabs/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. 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.

想法:

看到排好序的數組,首先就想到了用二分法。對於這道題目,就用目標值和首尾相加去比較,若目標值大,則首指針加1;否則尾指針減1。

代碼如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        
int low = 0,high = numbers.size() - 1; while (numbers[low] + numbers[high] != target) { if (numbers[low] + numbers[high] < target) low++; else high--; } vector<int> res{low + 1,high + 1};//由於返回的是原數組的第幾個,而不是下標,所以加1 return res; } };

大部分的排序數組問題都可以用二分法去解決。

【LeetCode】167. Two Sum II - Input array is sorted