-
LeetCode - Two SumProblem Solving/leetcode 2020. 9. 25. 17:03
문제 - 배열에서 target값이 주어지면 두 값을 더해서 target이되는 인덱스를 반환하는 문제
단, 오직 하나의 답만 존재
- 2 <= nums.length <= 105
- -109 <= nums[i] <= 109
- -109 <= target <= 109
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6 Output: [1,2]
Input: nums = [3,3], target = 6 Output: [0,1]
요즘 투포인터 문제를 연습하고 있어서 정렬하고 투포인터인가 생각했지만
그냥 해시맵 사용해서 푸는 문제였다
12345678910111213141516vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> mp;vector<int> ans;for(int i=0;i<nums.size();i++){int k=target-nums[i];if(mp.count(k)==0){mp[nums[i]]=i;}else{ans.push_back(mp[k]);ans.push_back(i);break;}}return ans;}cs 'Problem Solving > leetcode' 카테고리의 다른 글
Leecode - 2699. Modify Graph Edge Weights (1) 2023.05.26 Leetcode - Letter Combinations of a Phone Number (0) 2023.01.15 Leetcode - Longest Palindromic Substring (0) 2020.10.09 LeetCode - Longest Substring Without Repeating Characters (0) 2020.10.02