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
- Widget
- pytorch
- rao
- PCA
- BFS
- MDP
- system hacking
- BOF
- 영상처리
- 백준
- DART
- ARM
- Dreamhack
- Computer Architecture
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- study book
- fastapi를 사용한 파이썬 웹 개발
- MATLAB
- ML
- Image Processing
- Got
- BAEKJOON
- Algorithm
- C++
- Flutter
- Kaggle
- FastAPI
- Stream
- llm을 활용 단어장 앱 개발일지
- bloc
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를 통과하였다.