在将给定元素的第一次出现移动到 Q 查询的给定数组中结束后打印数组
给定一个包含N个整数的数组arr[]和一个包含Q个整数的数组query[] ,任务是在将第一次出现的query[i]移动到数组 arr[] 的末尾之后打印数组arr[ ] i在[0, Q)范围内。
例子:
Input: arr[] = {1, 3, 1, 3}, query[] = {3, 1}
Output: 1 3 3 1
Explanation: In 1st iteration, send first occurrence of query[0] to the end, i.e, send first occurrence of 3 to the end.
Hence, the array becomes arr[] = {1, 1, 3, 3}.
In 2nd iteration, send first occurrence of query[1] to the end.
Hence, array arr[] = {1, 3, 3, 1} which is the required array.
Input: arr[] = {1, 2, 3, 4, 5}, query[] = {4, 3}
Output: 1 2 5 4 3
方法:给定的问题可以使用散列来解决。这个想法是将每个整数的索引列表存储在一个集合数据结构中,并且对于当前整数的操作,从表示当前整数第一次出现的索引的集合中删除第一个索引并插入索引集合中的最后一个索引。以下是要遵循的步骤:
- 创建一个无序映射m ,存储每个索引的索引集。
- 迭代数组arr[]并将所有索引插入到映射m中它们各自的集合中。
- 使用变量 i 迭代数组query[]并执行以下操作:
- 从集合m[query[i]]中删除表示第一次出现的第一个元素。
- 将最后一个元素的索引,即N+i插入到集合m[query[i]]中。
- 按最终索引的升序打印元素,这是所需的答案。
下面是上述方法的实现:
C++14
// C++ program of the above approach
#include
using namespace std;
// Function to print the array after
// performing the given operations
void sendToLast(vector arr,
vector query)
{
// Stores index of present
// integers in a set
unordered_map > m;
// Loop to insert indices
// into the given map
for (int i = 0; i < arr.size(); i++) {
m[arr[i]].insert(i);
}
// Loop to iterate the
// query array
for (int i = 0; i < query.size(); i++) {
// Erase the index of current
// element from the map
m[query[i]].erase(*m[query[i]].begin());
// Insert new location
m[query[i]].insert(arr.size() + i);
}
// Vector of pair to store index
// value pair
vector > v;
// Insert all index value pair
// into the vector v
for (auto x : m) {
for (auto y : x.second) {
v.push_back({ y, x.first });
}
}
// Sort v in increasing order
// of the index
sort(v.begin(), v.end());
// Print array
for (int i = 0; i < v.size(); i++) {
cout << v[i].second << " ";
}
}
// Driver Code
int main()
{
vector arr{ 1, 3, 1, 3 };
vector query{ 3, 1 };
sendToLast(arr, query);
return 0;
}
Python3
# Python program for the above approach
# Function to print array after
# performing the given operations
def sendToLast(arr, query):
# Stores index of present
# integers in a set
m = {}
# Loop to insert indices
# into the given map
for i in range(len(arr)):
if arr[i] not in m:
m[arr[i]] = []
m[arr[i]].append(i)
# Loop to iterate the
# query array
for i in range(len(query)):
# Erase the index of current
# element from the map
m[query[i]] = m[query[i]][1:] #-.erase(*m[query[i]].begin())
# Insert new location
m[query[i]].append(len(arr) + i)
# Vector of pair to store index
# value pair
v =[]
# Insert all index value pair
# into the vector v
for x in m:
for y in m[x]:
v.append([y, x])
# Sort v in increasing order
# of the index
v.sort()
# Print array
for i in range(len(v)):
print(v[i][1], end = " ")
# Driver Code
arr = [1, 3, 1, 3]
query = [3, 1]
sendToLast(arr, query)
# This code is contributed by Shubham Singh
1 3 3 1
时间复杂度: O(Q * log N)
辅助空间: O(N)