🖥️ 시작하며
브루트 포스 방법으로 접근할 수 있다.
이중 for문
으로 순차적으로 모든 배열을 탐색하며 결괏값을 찾으면 된다. 조건에 You may assume that each input would have
exactly
one solution
,
라고 명시했으므로 쉬운 문제라 할 수 있다.⚙️ Python
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
⚙️ C++
class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { for (int i = 0; i < nums.size(); ++i) { for (int j = i + 1; j < nums.size(); ++j) { if (nums[i] + nums[j] == target) { return {i, j}; // 두 인덱스를 벡터로 반환 } } } return {}; } };
📌 소감
쉬운 문제다.
댓글