Leetcode第496题Next Greater Element I Java数组返回问题求助
Let's break down the issues in your code and fix them step by step:
First: Fix the Return Statement Syntax Error
Your current return line return new int[]{}array; is invalid Java syntax. You already converted your List<Integer> to an int[] called array using list.stream().mapToInt(i->i).toArray(); — you just need to return that array directly:
return array;
That's the quick fix for the immediate return error, but we still need to fix the core logic because your current approach doesn't solve the problem correctly.
Second: Fix the Next Greater Element Logic
Right now, you're only checking the immediately next element (nums2[j+1]) after finding nums1[i] in nums2. But the problem asks for the first element that's greater than the current element, anywhere after it in nums2 — not just the next one.
For example, if nums2 was [4,3,5] and nums1 has 4, your code would check 3 (which is smaller than 4) and add -1, but the correct next greater element is 5.
Here's how to fix the logic:
- After finding the position
jofnums1[i]innums2, loop from j+1 to the end of nums2 to find the first element that's larger thannums1[i]. - If we find such an element, add it to the list; if we reach the end without finding one, add
-1.
Full Corrected Code
public int[] nextGreaterElement(int[] nums1, int[] nums2) { List<Integer> list = new ArrayList<Integer>(); for (int num : nums1) { // Enhanced for-loop for cleaner code int indexInNums2 = -1; // First find the position of num in nums2 for (int j = 0; j < nums2.length; j++) { if (nums2[j] == num) { indexInNums2 = j; break; // No need to keep searching once found } } // Now find the next greater element after indexInNums2 int nextGreater = -1; for (int k = indexInNums2 + 1; k < nums2.length; k++) { if (nums2[k] > num) { nextGreater = nums2[k]; break; // Take the first one we find } } list.add(nextGreater); } // Convert list to int array and return it int[] result = list.stream().mapToInt(Integer::intValue).toArray(); // You can remove the print loop if you don't need it (LeetCode doesn't require printing) // for (int i = 0; i<result.length;i++){ // System.out.println(result[i]); // } return result; }
Key Improvements Explained
- Used enhanced for-loops for
nums1to make the code cleaner and easier to read. - Broke the logic into two clear steps: first locate the number in
nums2, then search for the next greater element. - Removed the unnecessary try-catch block (we can handle the "end of array" case explicitly by checking loop bounds, which is more efficient and readable).
- Return the correctly built
resultarray directly, matching the problem's requirement.
This code will now correctly return outputs like [-1,3,-1] as required by the problem.
内容的提问来源于stack exchange,提问作者Abdumutalibov

