167 Two Sum II - Input array is sorted 兩數之和 II - 輸入有序數組
阿新 • • 發佈:2018-04-07
數組 != 解決 升序 desc 一個 輸入 pub cpp
給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。
函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2。請註意,返回的下標值(index1 和 index2)不是從零開始的。
你可以假設每個輸入都只有一個解決方案,而且你不會重復使用相同的元素。
輸入:數組 = {2, 7, 11, 15}, 目標數 = 9
輸出:index1 = 1, index2 = 2
詳見:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { map<int,int> m; for(int i=0;i<numbers.size();++i) { auto p=m.find(target-numbers[i]); if(p!=m.end()) { return {p->second,i+1}; } m[numbers[i]]=i+1; } return {-1,-1}; } };
167 Two Sum II - Input array is sorted 兩數之和 II - 輸入有序數組