LeetCode 167. Two Sum II - Input array is sorted

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2 

Solution

  • 題意即給一個升序數組,並給出一個目標和,要求返回兩個下標,該組下標對應的數字和爲目標和.
  • 我的做法是用兩個遊標控制上下界,如果和大於目標和,就調整第二個遊標減小,小於的話,就調整第一個遊標增大,否則就是我們想要的結果.
  • 如果有遺漏之處,請不吝指教,十分感謝。代碼如下
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int i = 0,j = numbers.size() - 1;
        vector<int> rnt;

        while (i < j) {
            if (numbers[i] + numbers[j] == target) {
                rnt.push_back(i + 1);
                rnt.push_back(j + 1);
                break;
            }
            else if (numbers[i] + numbers[j] > target) {
                j--;
            }
            else {
                i++;
            }
        }
        return rnt;
    }
};
發佈了77 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章