https://leetcode.com/problems/two-sum/description/
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not
leetcode.com
- 코드 템플릿 : 1. Two pointers: one input, opposite ends
- Time complexity: O(n)
- 숙지할것:
1. Two pointers 는 SORTED 된 ARRAY에 바로 쓸수있으며 위 문제는 SORTED 가 되지않음
2. std::pair 포맷 숙지**
3. std::sort 포맷 숙지**
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int left=0;
int right = int(nums.size())-1;
vector<pair<int,int>> pair_v; // 포맷 숙지
for(int i= 0 ; i<nums.size(); i++){
pair_v.push_back({nums[i],i}); // push back 포맷숙지
}
sort(pair_v.begin(),pair_v.end()); //std::sort 포맷
while( left< right ){
int value = pair_v[left].first+pair_v[right].first;
if( value == target ){
return {pair_v[left].second,pair_v[right].second};
}
if(value<target){
left++;
}
else{
right--;
}
}
return {-1,-1};
}
};
// sort 가 안되있는 상태로 컨디션을 ??
'Data Structure & Algorithms > Arrays and Strings' 카테고리의 다른 글
[Arrrays and String] 713. Subarray Product Less Than K (투포인트와 슬라이딩 윈도우 개념 헷갈림) (0) | 2023.03.03 |
---|---|
[arrays and strings] 997.Squares of a Sorted Array (1) | 2023.03.01 |
[Arrays & String] 2회독 큰그림 잡기 - 자주쓰이는 템플릿정리 (0) | 2023.02.28 |
[Arrays] Container With Most Water (0) | 2022.10.11 |
[DSA] Array and String -Reverse String (1) | 2022.10.06 |
댓글