fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4.  
  5. class Solution {
  6. public:
  7. std::vector<int> nextGreaterElements(std::vector<int>& nums) {
  8. int n = nums.size();
  9. std::vector<int> result(n, -1); // Initialize result with -1
  10. std::stack<int> st; // Stack to keep track of indices
  11.  
  12. // Iterate through the array twice to simulate circular behavior
  13. for (int i = 0; i < 2 * n; ++i) {
  14. while (!st.empty() && nums[st.top()] < nums[i % n]) {
  15. result[st.top()] = nums[i % n];
  16. st.pop();
  17. }
  18. if (i < n) {
  19. st.push(i);
  20. }
  21. }
  22. return result;
  23. }
  24. };
  25.  
  26.  
  27.  
  28. void testNextGreaterElements() {
  29. Solution solution;
  30.  
  31. // Test case 1
  32. std::vector<int> nums1 = {1, 2, 1};
  33. std::vector<int> result1 = solution.nextGreaterElements(nums1);
  34. std::vector<int> expected1 = {2, -1, 2};
  35. std::cout << "Test 1 " << (result1 == expected1 ? "passed" : "failed") << std::endl;
  36.  
  37. // Test case 2
  38. std::vector<int> nums2 = {1, 2, 3, 4, 3};
  39. std::vector<int> result2 = solution.nextGreaterElements(nums2);
  40. std::vector<int> expected2 = {2, 3, 4, -1, 4};
  41. std::cout << "Test 2 " << (result2 == expected2 ? "passed" : "failed") << std::endl;
  42.  
  43. // Additional Test case 3
  44. std::vector<int> nums3 = {5, 4, 3, 2, 1};
  45. std::vector<int> result3 = solution.nextGreaterElements(nums3);
  46. std::vector<int> expected3 = {-1, 5, 5, 5, 5};
  47. std::cout << "Test 3 " << (result3 == expected3 ? "passed" : "failed") << std::endl;
  48.  
  49. // Additional Test case 4
  50. std::vector<int> nums4 = {8, 7, 9, 5, 6};
  51. std::vector<int> result4 = solution.nextGreaterElements(nums4);
  52. std::vector<int> expected4 = {9, 9, -1, 6, 8};
  53. std::cout << "Test 4 " << (result4 == expected4 ? "passed" : "failed") << std::endl;
  54.  
  55. // Additional Test case 5 (single element)
  56. std::vector<int> nums5 = {10};
  57. std::vector<int> result5 = solution.nextGreaterElements(nums5);
  58. std::vector<int> expected5 = {-1};
  59. std::cout << "Test 5 " << (result5 == expected5 ? "passed" : "failed") << std::endl;
  60. }
  61.  
  62. int main() {
  63. testNextGreaterElements();
  64. return 0;
  65. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Test 1 passed
Test 2 passed
Test 3 passed
Test 4 passed
Test 5 passed