본문 바로가기

Problem Solving/리트코드(leetcode)

[Leetcode/C++] 496. Next Greater Element 1


class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> answer;
        
        for(int i = 0; i < nums1.size(); i++) {
            int temp = 0;
            auto it = find(nums2.begin(),nums2.end(),nums1[i]) + 1;
            if(it != nums2.end()) {
                for(; it != nums2.end(); it++) {
                    if(*it > nums1[i]) {temp = *it; break;}
                }
                temp == 0 ? answer.push_back(-1) : answer.push_back(temp);
            } else {
                answer.push_back(-1);
                cout << "HERE?";
            }
        }
        return answer;
    }
};

algorithm 헤더에 있는 find 함수를 이용하여 찾고하자는 문자열이 있는 위치를 이터레이터로 받고 그것을 끝까지 돌리면서 가지고 있는 것보다 큰 친구가 나타나면 바로 break를 하도록 구현하였습니다.

 

그래서 만약 찾았다면 넣고 찾지 못했다면 -1을 넣도록 하였습니다.


문제: https://leetcode.com/problems/next-greater-element-i/

 

Next Greater Element I - 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