本文實例講述了java實現刪除排序數組中重復元素的方法。分享給大家供大家參考,具體如下:
題目描述:
給定一個排序數組,在原數組中刪除重復出現的數字,使得每個元素只出現一次,并且返回新的數組的長度。
不要使用額外的數組空間,必須在原地沒有額外空間的條件下完成。
一:通過arraylist解決
時間復雜度和空間復雜度都為o(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
arraylist<integer> list = new arraylist<integer>(); // 去掉數組中重復的元素 public int removetheagain01( int [] array) { if (array == null || array.length == 0 ) { return 0 ; } else if (array.length == 1 ) { return 1 ; } else { int i = 0 ; int n = array.length - 1 ; while (i <= n) { if (i == n) { list.add(array[i]); i++; } else { int j = i + 1 ; if (array[i] == array[j]) { while (j <= n && array[i] == array[j]) { j++; } } list.add(array[i]); i = j; } } for ( int k = 0 ; k < list.size(); k++) { array[k] = list.get(k); } return list.size(); } } |
二:利用system.arraycopy()函數來復制數組
時間復雜度為o(n^2),空間復雜度為o(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public int removetheagain02( int [] array) { if (array == null || array.length == 0 ) { return 0 ; } else if (array.length == 1 ) { return 1 ; } else { int end = array.length - 1 ; for ( int i = 0 ; i <= end; i++) { if (i < end) { int j = i + 1 ; if (array[i] == array[j]) { while (j <= end && array[i] == array[j]) { j++; } } system.arraycopy(array, j, array, i + 1 , end - j + 1 ); end -= j - i - 1 ; } } return end + 1 ; } } |
三:借助臨時變量解決問題
時間復雜度o(n),空間復雜度o(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public int removetheagain03( int [] array) { if (array == null || array.length == 0 ) { return 0 ; } else if (array.length == 1 ) { return 1 ; } else { int temp = array[ 0 ]; int len = 1 ; for ( int i = 1 ; i < array.length; i++) { if (temp == array[i]) { continue ; } else { temp = array[i]; array[len] = array[i]; len++; } } return len; } } |
總結:
數組下標(指針)與臨時變量,是解決數組相關面試題的兩大法寶**
ps:本站還有兩款比較簡單實用的在線文本去重復工具,推薦給大家使用:
在線去除重復項工具:https://tool.zzvips.com/t/quchong/
在線文本去重復工具:https://tool.zzvips.com/t/txtquchong/
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/wu2304211/article/details/52743589