167. Two Sum II - Input array is sorted

xiaoxiao2021-02-28  17

class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int ending = numbers.size() - 1; int temp; for(int i = 0; i <= ending; ++i){ int toFound = target - numbers[i]; int temp = search(numbers, i+1, ending, toFound); if(temp != -1){ ans.push_back(i+1); ans.push_back(temp+1); break; } } return ans; } int search(vector<int> &n, int low, int high, int target){ while(low <= high){ int mid = (low + high) / 2; if(n[mid] == target){ return mid; } else if(n[mid] > target) high = mid - 1; else low = mid + 1; } return -1; } };
转载请注明原文地址: https://www.6miu.com/read-750074.html

最新回复(0)