给定三种类型的Q查询,其中每个查询都由一个数字组成。
- 在左侧添加元素num
- 在右侧添加元素num
- 在给定元素num的左侧向右打印元素数。
任务是编写一个执行上述查询的程序。
注意:查询1和2中的元素是不同的,并且0 <= num <= 10 5 。
例子:
Input:
Q = 5
Query of type 1: num = 3
Query of type 2: num = 5
Query of type 1: num = 2
Query of type 1: num = 4
Query of type 3: num = 3
Output: element on the right: 1 element on the left: 2
After query 1, the element positioning is 3
After query 2, the element positioning is 35
After query 3, the element positioning is 235
After query 4, the element positioning is 4235
So there is 1 element to the right and 2 elements on the left of 3 when
query 3 is called.
可以按照以下步骤解决上述问题。
- 将变量left和right初始化为0,并初始化两个哈希数组position []和mark [] 。 position []用于在左侧和右侧存储num的索引,而mark []用于标记num在左侧或右侧。
- 对于查询1,增加left的计数,并将position [num]标记为left并将mark [num]标记为1。
- 对于查询2,增加right的计数,并将position [num]标记为right并将mark [num]标记为2
。
- 对于查询3,请使用mark []检查给定的数字在右侧还是左侧。
- 如果数字在右边,则num左边的元素数为(left-position [num]) ,num右边的元素数为(position [num] – 1 + right ) 。
- 如果左侧有数字,则num右侧的元素数将为(right-position [num]) ,而num左侧的元素数将为(position [num] – 1 + *左) 。
下面是上述方法的实现:
// C++ program to print the number of elements
// on right and left of a given element
#include
using namespace std;
#define MAXN 100005
// function to perform query 1
void performQueryOne(int num, int* left, int* right,
int* position, int* mark)
{
// count number of elements on left
*left = *left + 1;
// store the index number
position[num] = *(left);
// mark the element is on left
mark[num] = 1;
}
// function to perform query 2
void performQueryTwo(int num, int* left, int* right,
int* position, int* mark)
{
// count number of elements on right
*right = *right + 1;
// store the index number
position[num] = *(right);
// mark the element is on right
mark[num] = 2;
}
// function to perform query 3
void performQueryThree(int num, int* left, int* right,
int* position, int* mark)
{
int toright, toleft;
// if the element is on right
if (mark[num] == 2) {
toright = *right - position[num];
toleft = position[num] - 1 + *left;
}
// if the element is on left
else if (mark[num] == 1) {
toleft = *left - position[num];
toright = position[num] - 1 + *right;
}
// not present
else {
cout << "The number is not there\n";
return;
}
cout << "The number of elements to right of "
<< num << ": " << toright;
cout << "\nThe number of elements to left of "
<< num << ": " << toleft;
}
// Driver Code
int main()
{
int left = 0, right = 0;
// hashing arrays
int position[MAXN] = { 0 };
int mark[MAXN] = { 0 };
int num = 3;
// query type-1
performQueryOne(num, &left, &right, position, mark);
// query type-2
num = 5;
performQueryTwo(num, &left, &right, position, mark);
// query type-2
num = 2;
performQueryOne(num, &left, &right, position, mark);
// query type-2
num = 4;
performQueryOne(num, &left, &right, position, mark);
// query type-3
num = 3;
performQueryThree(num, &left, &right, position, mark);
return 0;
}
时间复杂度:每个查询为O(1)。
辅助空间: O(MAXN),其中MAXN是10 5 。
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。