본문 바로가기
개발/코딩

LeetCode - Two Sum / c++

by lucidmaj7 2020. 7. 24.
728x90
반응형

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

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);
                    goto EXIT;
                }
            }
        }
        EXIT:
        return result;
    }
};

 

두번째 답

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int,int> m;
        for(int i = 0 ;i<nums.size();i++)
        {
           m[nums[i]] = i;
        }
        
        for(int i = 0 ;i<nums.size();i++)
        {
            int diff = target- nums[i];
            if(m.find(diff)!=m.end())
            {
              if(m[diff] != i)
                {
                   result.push_back(m[diff]);
                  result.push_back(i);
                  break;
                }
            }
        }
        
        return result;
    }
};
728x90
반응형

댓글