题目
重新排列数组,使偶数位置的元素大于它之前的所有元素,奇数位置的元素小于它之前的所有元素。
Examples :
Input : arr[] = {1, 2, 3, 4, 5, 6, 7}
Output : 4 5 3 6 2 7 1
Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8}
Output : 4 5 2 6 1 8 1 8
方法1
public static void rearrangeArr(int []arr, int n)
{
int evenPos = n / 2;
int oddPos = n - evenPos;
int[] tempArr = new int [n];
for (int i = 0; i < n; i++)
tempArr[i] = arr[i];
Array.Sort(tempArr);
int j = oddPos - 1;
for (int i = 0; i < n; i += 2) {
arr[i] = tempArr[j];
j--;
}
j = oddPos;
for (int i = 1; i < n; i += 2) {
arr[i] = tempArr[j];
j++;
}
}
时间复杂度 : O(nlogn)
空间复杂度 : O(n)
方法2
public static void Main(String[] args)
{
int n, i, j, p, q;
int []a = {1, 2, 1, 4, 5, 6, 8, 8};
n = a.Length;
int []b = new int[n];
for(i = 0; i < n; i++)
b[i] = a[i];
Array.Sort(b);
p = 0; q = n - 1;
for(i = n - 1; i >= 0; i--)
{
if(i % 2 != 0)
{
a[i] = b[q];
q--;
}
else{
a[i] = b[p];
p++;
}
}
for(i = 0; i < n; i++)
{
Console.Write(a[i]+" ");
}
}
时间复杂度 : O(nlogn)
空间复杂度 : O(n)