Two Sum II - Input Array Is Sorted
1. Problem Statement
2. Algorithm Design and Approach
3. Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
int minIndex = 0;
int maxIndex = numbers.size() - 1;
for (; minIndex != maxIndex;)
{
int temp = numbers[minIndex] + numbers[maxIndex];
if (temp > target)
{
maxIndex--;
}
else if(temp < target)
{
minIndex++;
}
else
{
break;
}
}
return vector<int>{minIndex + 1, maxIndex + 1};
}
};
4. Example Walkthrough
5. Conclusion
- for 대신 While 문 사용 고려
- else if 대신 그냥 else만 쓰는게 더 시간단축
This post is licensed under CC BY 4.0 by the author.