寫一個查找算法找出數組中相同的元素


 1     import java.util.ArrayList;  
 2       
 3     public class Test {  
 4       
 5         // 原始數據data。假設data數組中的數據元素已經按照某種順序排好。  
 6         // 但是,該數組中的數據元素重復出現。  
 7         // 我們的目的是查找、解析data數組中重復出現的某元素。  
 8         // 比如,在這個data數組中,元素'C'在數組位置2,3重復出現兩次。  
 9         // 注意!有些元素沒有重復出現,比如元素'B'。  
10         private String[] data = { "A", "A", "B", "C", "C", "D", "D", "D" };  
11       
12         // 存儲分類好的數據元素。  
13         private ArrayList<Group> groups = new ArrayList<Group>();  
14       
15         // 核心的算法實現。  
16         public void find() {  
17       
18             // 游標index  
19             int index = 0, j = 0;  
20       
21             while (index < data.length) {  
22                 Group group = new Group();  
23                 group.title = data[index];  
24                   
25                 String t = group.title;  
26       
27                 ArrayList<String> children = new ArrayList<String>();  
28       
29                 for (j = index; j < data.length; j++) {  
30       
31                     String child = data[j];  
32                     if (t.equals(child)) {  
33                         // 同時記錄該重復出現的元素在原數組中的下標j,便於查驗、評估結果。  
34                         children.add(child + "@" + j);  
35                     } else {  
36                         break;  
37                     }  
38                 }  
39       
40                 // 往后推進游標index  
41                 index = j;  
42       
43                 group.children = children;  
44                 groups.add(group);  
45             }  
46         }  
47       
48         // 輸出結果。  
49         private void print() {  
50             for (int i = 0; i < groups.size(); i++) {  
51                 Group g = groups.get(i);  
52                 System.out.println(g);  
53             }  
54         }  
55       
56         // 自己構造一個類,作為一組數據的容器。  
57         // 該類用一個title表明這一group數據是歸屬於那個重復元素的組。  
58         // 該title下重復的元素裝入到ArrayList<String> children中,供遍歷查詢。  
59         private class Group {  
60             public String title;  
61             public ArrayList<String> children;  
62       
63             // 結果。  
64             @Override  
65             public String toString() {  
66                 String str = "組" + title + ": ";  
67                 for (int i = 0; i < children.size(); i++) {  
68                     str += children.get(i) + " ";  
69                 }  
70       
71                 return str;  
72             }  
73         }  
74       
75         public static void main(String args[]) {  
76             Test t = new Test();  
77             t.find();  
78             t.print();  
79         }  
80     }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM