https://leetcode.com/problems/next-greater-element-i/description/
Next Greater Element I - LeetCode
Can you solve this real interview question? Next Greater Element I - The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1
leetcode.com
전수조사 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 ans를 선언해 줍니다.
📔 풀이과정
num1의 원소를 1차, nums2의 원소를 2차로 총 2차원 for loop를 수행합니다.
1. nums1[i]와 nums2[j]가 같은 index를 찾습니다. 그 값을 first에 저장해줍니다.
2. first + 1부터 nums2.size()까지 다시 loop를 돌며 nums1[i]보다 큰 값을 second에 저장해줍니다. 중간에 찾았다면 second를 갱신, 찾았음을 나타내는 find변수를 1로 만들어줍니다.
3. 찾은 경우 second위치에 맞는 nums2원소를 ans에 push_back해줍니다. 찾지 못했다면 -1을 넣어줍니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
    
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector <int> ans;
        for(int i = 0; i < nums1.size(); i++) {
            int first = 0;
            for(int j = 0; j < nums2.size(); j++) {
                if(nums1[i] == nums2[j]) {
                    first = j;
                    break;
                }
            }
            int find = 0, second = 0;
            for(int j = first + 1; j < nums2.size(); j++) {
                if(nums2[j] > nums1[i]) {
                    second = j;
                    find = 1;
                    break;
                }
            }
            if(!find) {
                ans.push_back(-1);
            }
            else {
                ans.push_back(nums2[second]);
            }
        }
        return ans;
    }
};*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Brute Force' 카테고리의 다른 글
| (C++) - LeetCode (easy) 507. Perfect Number (0) | 2023.04.09 | 
|---|---|
| (C++) - LeetCode (easy) 500. Keyboard Row (0) | 2023.04.04 | 
| (C++) - LeetCode (easy) 463. Island Perimeter (0) | 2023.03.24 | 
| (C++) - LeetCode (easy) 1539. Kth Missing Positive Number (0) | 2023.03.06 | 
| (C++) - LeetCode (easy) 401. Binary Watch (0) | 2023.03.03 |