LeetCode 1. Two Sum

margarin·2021년 2월 12일
0

알고리즘

목록 보기
4/13

문제

👉 1. 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 use the same element twice.

You can return the answer in any order.

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

풀이방법

하나씩 돌아가면서 2개의 수가 target과 일치하는지 계산하였다.
먼저 하나의 수(now)를 선택 다음, (target - now)의 값이 배열에 존재한다면 벡터에 추가하였다.

코드

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        for (int i = 0; i < nums.size(); i++) {
            int now = nums[i];
            result.push_back(i);
            for (int j = i+1; j < nums.size(); j++) {
                int remain = target - now;
                if ( nums[j] == remain) {
                    result.push_back(j);
                    return result;
                }
            }
            result.pop_back();
        }
        return result;
    }
};
profile
화이팅 🥹

0개의 댓글