Every day a leetcode
题目来源:496. 下一个更大元素 I
解法1:遍历
遍历数组nums1的每一个元素值number,逐个在数组nums2中对应位置(即nums2[j] == number)的右边的第一个比number大的元素值。
代码:
/*
* @lc app=leetcode.cn id=496 lang=cpp
*
* [496] 下一个更大元素 I
*/
// @lc code=start
class Solution
{
public:
vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2)
{
vector<int> ans;
int n1 = nums1.size();
int n2 = nums2.size();
for (int i = 0; i < n1; i++)
{
int number = nums1[i];
int j = 0;
while (j < n2 && nums2[j] != number)
j++;
j++;
while (j < n2 && nums2[j] <= number)
j++;
if (j == n2)
ans.push_back(-1);
else
ans.push_back(nums2[j]);
}
return ans;
}
};
// @lc code=end
结果:

复杂度分析:
时间复杂度:O(mn),其中m是数组nums1的长度,n是数组nums2的长度。
空间复杂度:O(1)。
该文章介绍了LeetCode第496题的解法,通过遍历数组nums1并在数组nums2中寻找每个元素右侧的第一个更大元素。当找不到时,返回-1。时间复杂度为O(mn),空间复杂度为O(1)。
857

被折叠的 条评论
为什么被折叠?



