题目:编写一个方法,删除有序数组中的重复元素。例如:数组:1,2,2,4,5,5,5,8,9,9,10。删除重复元素后:1,2,4,5,8,9,10。
RemoveRepeatItem.java
1 public class RemoveRepeatItem { 2 /** 3 * 单元测试 4 */ 5 public static void main(String[] args){ 6 int[] sortArr = { 1,3,3,4,5,5,5,7,8,9,9,9 }; 7 int[] arr = removeRepeat(sortArr); 8 for(int item : arr){ 9 System.out.print(item + " ");10 }11 }12 13 /**14 * 删除有序数组中重复元素15 */16 public static int[] removeRepeat(int[] a){17 int N = a.length;18 int[] arr = new int[N];19 for(int i = 0;i < N; i++){20 arr[i] = a[i]; //保护性复制21 }22 int len = N;23 for(int i = 0; i < len; i++){24 //记录重复元素个数25 int repeatCnt = 0;26 for(int j = i + 1;j < len;j++){27 if(arr[j] == arr[i]){28 //如果重复,repeatCnt加129 repeatCnt++;30 } else if(arr[j] > arr[i]){31 //及时跳出循环32 break;33 }34 }35 //如果重复,开始移动元素36 if(repeatCnt > 0){37 for(int k = i + repeatCnt + 1; k < len;k++){38 arr[k - repeatCnt] = arr[k];39 }40 //数组长度减小41 len = len - repeatCnt;42 } 43 }44 45 //结果数组46 int[] result = new int[len];47 for(int i = 0;i < len; i++){48 result[i] = arr[i];49 }50 51 return result;52 }53 }