본문 바로가기

알고리즘 · 코딩

[LeetCode] Two Sum

[LeetCode] 1. Two Sum

 

문제 링크

https://leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

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

 

Integer 배열인 nums와 Integer인 target이 주어진다.

nums 배열 원소들 중 두 개를 골라 더한 값이 target일 때, 두 원소의 index를 배열에 담아 리턴하는 문제였다.

 

* 단 같은 수를 두번 사용할 수 없으며, 한가지 방법만 존재함이 보장된다.

 

Example

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

C++ 풀이

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>answer = {};
        int nums_size = nums.size();
        for (int i = 0; i < nums_size; ++i) {
            for (int j = i + 1; j < nums_size; ++j) {
                if (nums[i] + nums[j] == target) {
                    answer.push_back(i);
                    answer.push_back(j);
                    break;
                }
            }
        }
        return answer;
    }
};

반복문을 돌려서 간단하게 풀이해보았다.

LeetCode는 처음인데 다양한 문제 형식이 많아서 좋은 것 같다.

 

 

LIST