给定一个数组(或字符串),任务是反转数组/字符串。
Examples :
Input : arr[] = {4, 5, 1, 2}
Output : arr[] = {2, 1, 5, 4}
- 将开始和结束索引初始化为 start = 0, end = n-1
- 在循环中,将 arr[start] 与 arr[end] 交换并更改 start 和 end 如下:
开始 = 开始 +1,结束 = 结束 - 1
using System;class Arrangement1 {public static void rvereseArray(int []arr,int start, int end){int temp;while (start < end){temp = arr[start];arr[start] = arr[end];arr[end] = temp;start++;end--;}} public static void printArray(int []arr,int size){for (int i = 0; i < size; i++)Console.Write(arr[i] + " ");Console.WriteLine();}
}
时间复杂度 : O(n)
- 将开始和结束索引初始化为 start = 0, end = n-1
- 将 arr[start] 与 arr[end] 交换
- 对数组的其余部分递归调用 reverse。
static void rvereseArray(int []arr, int start, int end)
{int temp;if (start >= end)return;temp = arr[start];arr[start] = arr[end];arr[end] = temp;rvereseArray(arr, start+1, end-1);
}
时间复杂度 : O(n)