std::set + sorting in O(NlogN) || C++
[Solution]\nLet\'s simplify the statement first.\n\nThis problem can be reduced to finding the second greater index from subset of index S of which index-th ele
**[Solution]**\nLet\'s simplify the statement first.\n\nThis problem can be reduced to finding the second greater index from subset of index S of which index-th element of nums is strictly greater than nums[i], for each i in range of [0, N), \n\nIf we iterate over an array based on preference of pair<int, int>{-nums[i], i},\n\nthis can be reduced to finding the second greater index from subset of index S of which index is previously iterated, for each pair<int, int>{-nums[i], i}.\n\n\nThe problem get much simpler, and it can be easily implemented by using std::set and its module, upper_bound() twice!\n\nIf you use other languages which does not support the same kind of the std:: map data structure, it may be more difficult, though.\n\nAnyway, here\'s my implementation in C++.\n\nTime : O(NlogN)\nSpace: O(N)\n\n```\nclass Solution {\npublic:\n    vector<int> secondGreaterElement(vector<int>& nums) {\n        const int n = nums.size();\n        vector<pair<int, int>> arr(n);\n        for (int i = 0; i < n; i++){\n            arr[i] = {-nums[i], i};\n        }\n        sort(arr.begin(), arr.end());\n        set<int> S;\n        vector<int> ans(n, -1);\n        for (auto & [_, idx] : arr){\n            auto itr = S.upper_bound(idx);\n            if (itr != S.end()){\n                auto itr1 = S.upper_bound(*itr);\n                if (itr1 != S.end()){\n                    ans[idx] = nums[*itr1];\n                }\n            }\n            S.insert(idx);\n        }\n        return ans;\n    }\n};\n```
['Sorting', 'Ordered Set']