-
[LeetCode] 167. Two Sum II - Input Array Is Sorted c++Coding Test/LeetCode 2022. 12. 26. 16:18728x90
- 문제
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
numbers[index1] + numbers[index2] = target 이 되는 index1 , 2를 구하는 문제이다.
- 문제 해결
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int len = numbers.size(); for(int i = 0; i < len - 1; i++){ int lo = i + 1; int hi = len; while( lo < hi){ int mid = lo + ( hi - lo ) / 2; if(numbers[mid] == target - numbers[i]){ return {i + 1, mid + 1}; } else if(numbers[mid] >= target - numbers[i]){ hi = mid; } else{ lo = mid + 1; } } if(lo != numbers.size() && numbers[lo] == target - numbers[i]){ return {i + 1, lo + 1}; } } return {}; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 557. Reverse Words in a String III c++ (0) 2022.12.26 [LeetCode] 344. Reverse String c++ (0) 2022.12.26 [LeetCode] 283. Move Zeroes c++ (0) 2022.12.24 [LeetCode] 606. Construct String from Binary Tree c++ (0) 2022.12.24 [LeetCode] 144. Binary Tree Preorder Traversal c++ (0) 2022.12.23