C++ | O(nlogn) | set
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- T
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> secondGreaterElement(vector<int>& nums) {\n        int n = nums.size();\n\t\tvector<pair<int, int>> a(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ta[i] = {nums[i], i};\n\t\t}\n\t\tsort(a.begin(), a.end(), [](const pair<int, int> &x, const pair<int, int> &y) {\n\t\t\treturn x.first != y.first ? x.first > y.first : x.second > y.second;\n\t\t});\n\t\tvector<int> firstGreater(n, -1), secondGreater(n, -1), ans(n, -1);\n\t\tset<int> st;\n\t\tfor (const pair<int, int> &p: a) {\n\t\t\tint i = p.second;\n\t\t\tauto it = st.upper_bound(i);\n\t\t\tif (it != st.end()) {\n\t\t\t\tint j = *it;\n\t\t\t\tif (nums[j] == nums[i]) {\n\t\t\t\t\tfirstGreater[i] = firstGreater[j];\n\t\t\t\t\tsecondGreater[i] = secondGreater[j];\n\t\t\t\t} else {\n\t\t\t\t\tfirstGreater[i] = j;\n\t\t\t\t\tif (++it != st.end()) {\n                        j = *it;\n\t\t\t\t\t\tif (nums[j] == nums[i]) {\n\t\t\t\t\t\t\tsecondGreater[i] = firstGreater[j];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsecondGreater[i] = j;\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (secondGreater[i] > -1) {\n\t\t\t\tans[i] = nums[secondGreater[i]];\n\t\t\t}\n\t\t\tst.insert(i);\n\t\t}\n\t\treturn ans;\n    }\n};\n```
['C++']