检查 Array 是否可以使用给定的操作以非递减顺序排序
给定一个由正整数组成的大小为N的数组arr[] ,任务是通过执行以下操作检查数组是否可以按非递减顺序排序:
- 选择两个相邻的元素。
- 交换元素并反转它们的符号。
- 最后收到的排序数组中的所有元素都必须是正数。
例子:
Input: N = 4, arr[] = [4, 3, 2, 5]
Output: true
Explanation: In the given array, perform the following operations:
Swap arr[0] and arr[1] updated array: [-3, -4, 2, 5]
Swap arr[1] and arr[2] updated array: [-3, -2, 4, 5]
Swap arr[1] and arr[0] updated array: [2, 3, 4, 5]
The array is sorted in non-decreasing order and the elements are all positive.
Input: N = 4, arr[] = [3, 3, 2, 2]
Output: true
Explanation: In the given array, perform the following operations :
Swap arr[0] and arr[2] updated array: [-2, 3, -3, 2]
Swap arr[1] and arr[3] updated array: [-2, -2, -3, -3]
Swap arr[1] and arr[0] updated array: [2, 2, -3, -3]
Swap arr[2] and arr[3] updated array: [2, 2, 3, 3]
The array is sorted in non-decreasing order and the elements are all positive.
Input: N = 5, arr[] = [1, 2, 3, 5, 4]
Output: false
Explanation: There is no way to sort the array such that it follows all the mentioned conditions.
方法:问题可以通过 基于以下观察的贪心方法:
Each number needs to move an even distance because they should all be positive at the end. And a positive number remains positive only after even number of invresion of signs.
So the difference of distance for all array elements between the given one and the sorted array must be even.
请按照以下步骤解决此问题:
- 初始化一个空映射(例如ctr[2][] )以将数组元素的频率保持在偶数位置和奇数位置。
- 遍历数组arr并将ctr[i % 1][arr[i]]增加 1
- 对数组arr[]进行排序。
- 遍历数组arr[]并将ctr[i % 1][arr[i]]减 1。
- 遍历数组arr[] ,如果ctr[1][a[i]] ≠ 0或ctr[0][a[i]] ≠ 0 ,则返回 false。
- 否则,如果迭代完成,则返回 true。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to find if it is possible
// to sort the array in non-decreasing order
bool isItPossible(int n, vector& a)
{
// Initializing a map 'ctr'.
map ctr[2];
// Iterating over an array and updating
// the count for each occurrence
for (int i = 0; i < n; i++) {
ctr[i % 2][a[i]]++;
}
// Sorting out the array
sort(a.begin(), a.end());
// Updating count again according the
// sorted array
for (int i = 0; i < n; i++) {
ctr[i % 2][a[i]]--;
}
// Iterating over array again and if the
// count is not zero then returning false
for (int i = 0; i < n; i++) {
if (ctr[0][a[i]] != 0 || ctr[1][a[i]] != 0) {
return false;
}
}
return true;
}
// Driver code
int main()
{
int N = 4;
vector arr = { 3, 3, 2, 2 };
// Function call
cout << boolalpha
<< isItPossible(N, arr);
return 0;
}
true
时间复杂度: O(N * log(N))
辅助空间: O(N)