Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 28 | 29 | 30 |
31 |
Tags
- FastAPI
- Stream
- PCA
- ARM
- bloc
- MDP
- BFS
- BAEKJOON
- study book
- Dreamhack
- Kaggle
- 영상처리
- ML
- Widget
- Algorithm
- rao
- llm을 활용 단어장 앱 개발일지
- Computer Architecture
- BOF
- 백준
- pytorch
- DART
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- fastapi를 사용한 파이썬 웹 개발
- Image Processing
- Flutter
- MATLAB
- Got
- C++
- system hacking
Archives
- Today
- Total
Bull
[LeetCode] 1. Two Sum (C++) 본문
https://leetcode.com/problems/two-sum/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};
input으로 nums 벡터와 target 을 받은 후, nums 벡터에 있는 원소들 중 2개의 합이 target이 되는 인덱스를 구해서 반환하는 문제이다.
해결 방법
1번 문제에 난이도는 easy인 만큼 쉬울 것으로 예상이 됐다.
백준처럼 시간초과는 걸리지 않을 것 같아서 반복문을 2번 적용하여 각 원소별로 더하여 그 값이 target이 되는 모든 경우의 수를 구하는 방향으로 가보자.
코드
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0; i<nums.size(); i++){
for(int j = i+1; j<nums.size(); j++){
if(nums[i]+nums[j]==target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
조건문을 통해 단순하게 원소의 합이target이 되면 result<int> 벡터에 i와 j의 값을 push 하였다.
반환값이 존재하는 함수이므로 조건문 외에 마지막에 result를 반환하였다.
결과
모든 case를 통과하였다.