下面有四个问题:
- 把数组元素前后部分交换 MoveFirstPartOfArrayToTheEnd(int[] array, int index) 比如 {1,2,3,4,5,6,7} 3 => {4,5,6,7,1,2,3}
- 把数组元素前后部分交换 MoveFirstPartOfArrayToTheEnd(int[] array, int value)比如 {1,2,8,4,5,6,7} 8 => {4,5,6,7,1,2,8}
- 把数组一段移动到后面MoveSomeElementsToTheEnd(int[] array, int startIndex, int length)比如{1,2,3,4,5,6,7,8} 3 3 => {1,2,3,7,8,4,5,6}
- 把数组中重复的元素变成0放到最后面RemoveDulplicatedElements(int[] array) 比如 {1,3,3,2,4,4,4,5} => {1,3,2,4,5,0,0,0}
你首先想到的办法是什么?
- 申请一个临时数组把FistPart和EndPart交换
- 同上,只要找到对应值的下标即可。
- 同上申请临时数组,把要移动的段放到临时数组里
- 申请一个临时的List<int>把唯一的元素加到List里面,再重新赋给Array。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //1 6 int[] array1 = { 1, 2, 3, 4, 5, 6, 7 }; 7 MoveFirstPartOfArrayToTheEnd(array1, 3); 8 printArray(array1); 9 10 //2 11 int[] array2 = { 1, 2, 8, 4, 5, 6, 7 }; 12 MoveFirstPartOfArrayToTheEndValue(array2, 8); 13 printArray(array2); 14 15 //3 16 int[] array3 = { 1, 2, 3, 4, 5, 6, 7, 8 }; 17 MoveSomeElementsToTheEnd(array3, 3, 3); 18 printArray(array3); 19 20 //4 21 int[] array4 = { 1, 3, 3, 2, 4, 4, 4, 5 }; 22 removeDulplicatedElements(array4); 23 printArray(array4); 24 25 } 26 27 private static void printArray(int[] array) 28 { 29 for (int i = 0; i < array.Length; i++) 30 { 31 Console.Write(array[i]); 32 } 33 Console.WriteLine(); 34 } 35 36 public static void MoveFirstPartOfArrayToTheEnd(int[] array, int index) 37 { 38 if (index >= array.Length || index <= 0) 39 { 40 throw new Exception("index must be greater than 0 and less than " + array.Leng