
在这个问题中,我们通过每轮执行给定的操作将数组大小减少到 1 或 0。
我们可以在每一轮中对数组进行排序,以获得每次迭代中的最大元素。另外,我们还可以使用head数据结构来提高代码的性能。
问题陈述 - 我们给出了一个 nums[] 数组。我们需要通过执行以下操作来减少数组。
打印数组的最后一个元素。如果数组为空,则打印 0。
示例
输入
nums = {5, 9, 8, 3, 2, 5};
输出
0
说明
在第一轮中,我们取 9 和 8 并将其差值添加到数组中。因此,数组变为 [5, 3, 2, 5, 1]。
在第二轮中,我们取 5 和 5。因此,数组变为 [3, 2, 1]。
下一轮,我们取 3 和 2。因此,数组变为 [1, 1]
在最后一轮中,我们取 1 和 1。因此,数组变为空,我们打印 0。
输入
nums = {5, 5, 5, 5, 5};
输出
5
解释- 我们两次删除一对 5,并且有一个 5 保留在数组中。
输入
nums = {4, 8, 7, 6};
输出
1
解释 - 首先,我们选择 8 和 7。因此,数组变为 [4, 1, 6]。之后,我们选择4和6。因此,数组变为[1, 2]。在最后一次操作中,数组变为[1]。
方法 1
在这种方法中,我们将遍历数组,直到数组的大小变为 1 或 0。在每次迭代中,我们将对数组进行排序并对已排序数组的前 2 个元素执行给定的操作。最后,我们将根据数组大小打印输出。
算法
第 1 步- 将数组的大小存储在“len”变量中。
步骤 2- 开始使用 while 循环遍历数组。
第 3 步- 在循环中使用 sort() 方法对数组进行相反的排序。
第 4 步- 获取数组的第一个和第二个元素。另外,计算数组的第一个和第二个元素之间的差异。
第 5 步− 如果差值为 0,则删除数组的前两个元素,并将 'len' 减少 2。如果差值不为 0,则删除前 2 个元素并减少'len' 减 1。
第6步- 最后,如果数组的大小为0,则返回0。否则,返回数组的第一个元素。
示例
#include <bits/stdc++.h>
using namespace std;
int findLast(vector<int> &nums) {
int len = nums.size();
int p = 0;
while (len > 1) {
// Sort array in reverse order
sort(nums.begin(), nums.end(), greater<int>());
// Take the first and second elements of the array
int a = nums[0];
int b = nums[1];
// Take the difference between the first and second element
int diff = a - b;
if (diff == 0) {
nums.erase(nums.begin());
nums.erase(nums.begin());
len -= 2;
} else {
nums.erase(nums.begin());
nums.erase(nums.begin());
nums.push_back(diff);
len -= 1;
}
}
// When the size of the array is 0
if (nums.size() == 0)
return 0;
return nums[0];
}
int main() {
vector<int> nums = {5, 9, 8, 3, 2, 5};
cout << "The last remaining element after performing the given operations is " << findLast(nums) << "
";
return 0;
}
输出
The last remaining element after performing the given operations is 0
时间复杂度 - O(N*NlogN),其中 O(N) 用于遍历数组,O(NlogN) 用于在每次迭代中对数组进行排序。
空间复杂度 - O(N) 对数组进行排序。
方法2
在这种方法中,我们将使用优先级队列,它实现了堆数据结构。它始终按排序顺序存储元素。因此,我们可以轻松删除前 2 个最大元素。
算法
第 1 步- 定义名为优先级队列的“p_queue”。
步骤 2- 将所有数组元素插入优先级队列。
步骤 3- 进行迭代,直到优先级队列的大小大于 1。
步骤 4- 逐一删除优先级队列的前 2 个元素。
第 5 步- 求两个元素之间的差异。
第6步- 如果差值不为0,则将其推入优先级队列。
第 7 步− 最后,如果队列大小为 0,则返回 0。
第 8 步- 否则,返回队列顶部的元素。
示例
#include <bits/stdc++.h>
using namespace std;
int findLast(vector<int> &nums) {
// Defining a priority queue
priority_queue<int> p_queue;
// Inserting array elements in priority queue
for (int p = 0; p < nums.size(); ++p)
p_queue.push(nums[p]);
// Make iterations
while (p_queue.size() > 1) {
// Take the first element from queue
int first = p_queue.top();
p_queue.pop();
// Get the second element from queue
int second = p_queue.top();
p_queue.pop();
// Take the difference of first and second elements
int diff = first - second;
if (diff != 0)
p_queue.push(diff);
}
// When queue is empty
if (p_queue.size() == 0)
return 0;
// Return the last remaining element
return p_queue.top();
}
int main() {
vector<int> nums = {5, 9, 8, 3, 2, 5};
cout << "The last remaining element aft
.........................................................