Python3 程序查找范围和查询,以按 K 索引对 Array 进行逆时针旋转
给定一个包含N个元素的数组arr和以下两种类型的Q个查询:
- 1 K :对于这种类型的查询,数组需要从当前状态逆时针旋转K个索引。
- 2 LR :对于此查询,需要计算索引[L, R]中存在的数组元素的总和。
例子:
Input: arr = { 1, 2, 3, 4, 5, 6 }, query = { {2, 1, 3}, {1, 3}, {2, 0, 3}, {1, 4}, {2, 3, 5} }
Output:
9
16
12
Explanation:
For the 1st query {2, 1, 3} -> Sum of the elements in the indices [1, 3] = 2 + 3 + 4 = 9.
For the 2nd query {1, 3} -> Modified array after anti-clockwise rotation by 3 places is { 4, 5, 6, 1, 2, 3 }
For the 3rd query {2, 0, 3} -> Sum of the elements in the indices [0, 3] = 4 + 5 + 6 + 1 = 16.
For the 4th query {1, 4} -> Modified array after anti-clockwise rotation by 4 places is { 2, 3, 4, 5, 6, 1 }
For the 5th query {2, 3, 5} -> Sum of the elements in the indices [3, 5] = 5 + 6 + 1 = 12.
方法:
- 创建一个大小为arr两倍的前缀数组,并将arr的第i个索引处的元素复制到[0, N)中所有 i 的第i个和第N + i个前缀索引。
- 为该数组的每个索引预先计算前缀和并存储在前缀中。
- 将指针设置为从0开始以表示初始数组的起始索引。
- 对于类型 1 的查询,将start移至
((start + K) % N)th position
- 对于类型 2 的查询,计算
prefix[start + R]
- prefix[start + L- 1 ]
- 如果start + L >= 1或打印的值
prefix[start + R]
- 除此以外。
下面的代码是上述方法的实现:
Python3
# Python3 program to calculate range sum
# queries for anticlockwise
# rotations of the array by K
# Function to execute the queries
def rotatedSumQuery(arr, n, query, Q):
# Construct a new array
# of size 2*N to store
# prefix sum of every index
prefix = [0] * (2 * n)
# Copy elements to the new array
for i in range(n):
prefix[i] = arr[i]
prefix[i + n] = arr[i]
# Calculate the prefix sum
# for every index
for i in range(1, 2 * n):
prefix[i] += prefix[i - 1];
# Set start pointer as 0
start = 0;
for q in range(Q):
# Query to perform
# anticlockwise rotation
if (query[q][0] == 1):
k = query[q][1]
start = (start + k) % n;
# Query to answer range sum
elif (query[q][0] == 2):
L = query[q][1]
R = query[q][2]
# If pointing to 1st index
if (start + L == 0):
# Display the sum upto start + R
print(prefix[start + R])
else:
# Subtract sum upto start + L - 1
# from sum upto start + R
print(prefix[start + R]-
prefix[start + L - 1])
# Driver code
arr = [ 1, 2, 3, 4, 5, 6 ];
# Number of query
Q = 5
# Store all the queries
query= [ [ 2, 1, 3 ],
[ 1, 3 ],
[ 2, 0, 3 ],
[ 1, 4 ],
[ 2, 3, 5 ] ]
n = len(arr);
rotatedSumQuery(arr, n, query, Q);
# This code is contributed by ankitkumar34
9
16
12
时间复杂度:每个查询O(1) 。
辅助空间复杂度: O(N)
有关更多详细信息,请参阅关于数组逆时针旋转 K 索引的范围和查询的完整文章!