给定一个长度为N的数组 A[] ,任务是通过最多交换每个索引的相邻元素一次来找到字典序最小的数组。因此,对于任何索引:
,最多允许在 A[K] 和 A[K+1] 之间进行一次交换。
例子:
Input: A[] = { 3, 2, 1, 4}
Output: 1 3 2 4
Explanation: Perform the following swaps:
Swap A[1] and A[2], now A[] = { 3, 1, 2, 4 }
Swap A[0] and A[1], now A[] = { 1, 3, 2, 4 }
No further swaps are possible as A[1] and A[2] have already been swapped.
Input: A[] = { 2, 1, 4, 3, 6, 5 }
Output: 1 2 3 4 5 6
Explanation: Perform the following swaps:
Swap A[0] and A[1], now A[] = { 1, 2, 4, 3, 6, 5 }
Swap A[2] and A[3], now A[] = { 1, 2, 3, 4, 6, 5 }
Swap A[4] and A[5], now A[] = { 1, 2, 3, 4, 5, 6 }
方法:
为了解决上面提到的问题,我们可以应用贪心法。我们知道我们最多可以执行N-1 次交换来使给定的数组尽可能小。
- 创建一个计数器变量并使用 N-1 和哈希映射进行初始化以存储执行的交换。
- 从当前索引开始查找最小元素的位置。
- 现在向后执行交换,直到我们到达当前元素位置。
- 还要检查当前交换是否可能,并在每次交换时递减计数器。
- 最后打印所需的数组。
下面是上述方法的实现:
C++
// C++ implementation to find the
// lexicographically smallest
// array by at most single swap
// for every pair of adjacent indices
#include
using namespace std;
// Function to find the
// lexicographically smallest array
void findSmallestArray(int A[], int n)
{
// maximum swaps possible
int count = n - 1;
// hash to store swaps performed
map, int> mp;
for (int i = 0; i < n && count > 0; ++i) {
// let current element be
// the minimum possible
int mn = A[i], pos = i;
// Find actual position of
// the minimum element
for (int j = i + 1; j < n; ++j) {
// Update minimum element and
// its position
if (A[j] < mn) {
mn = A[j];
pos = j;
}
}
// Perform swaps if possible
while (pos > i && count > 0
&& !mp[{ pos - 1, pos }]) {
// Insert current swap in hash
mp[{ pos - 1, pos }] = 1;
swap(A[pos], A[pos - 1]);
--pos;
--count;
}
}
// print the required array
for (int i = 0; i < n; ++i)
cout << A[i] << " ";
}
// Driver code
int main()
{
int A[] = { 2, 1, 4, 3, 6, 5 };
int n = sizeof(A) / sizeof(A[0]);
findSmallestArray(A, n);
return 0;
}
Python3
# Python3 implementation to find the
# lexicographically smallest array by
# at most single swap for every pair
# of adjacent indices
# Function to find the
# lexicographically smallest array
def findSmallestArray(A, n):
# Maximum swaps possible
count = n - 1
# Hash to store swaps performed
mp = {''}
for i in range(0, n):
if(count <= 0):
break;
# Let current element be
# the minimum possible
mn = A[i]
pos = i
# Find actual position of
# the minimum element
for j in range(i + 1, n):
# Update minimum element
# and its position
if (A[j] < mn):
mn = A[j]
pos = j
# Perform swaps if possible
while (pos > i and count > 0 and
((pos - 1, pos) not in mp)):
# Insert current swap in hash
mp.add((pos - 1, pos))
A[pos], A[pos - 1] = A[pos - 1], A[pos]
pos -= 1
count -= 1
# Print the required array
for i in range(0, n):
print(A[i], end = " ")
# Driver code
A = [ 2, 1, 4, 3, 6, 5 ]
n = len(A)
findSmallestArray(A, n)
# This code is contributed by Sanjit_Prasad
1 2 3 4 5 6
时间复杂度: O(N 2 )
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。