算法--判斷數組中是否有重復值


 


判斷數組中是否有重復值

 
 

第14節 重復值判斷練習題

 

請設計一個高效算法,判斷數組中是否有重復值。必須保證額外空間復雜度為O(1)。

給定一個int數組A及它的大小n,請返回它是否有重復值。

測試樣例:
[1,2,3,4,5,5,6],7
返回:true
 
 
1
import java.util.*;
2
 
                        
3
public class Checker {
4
    public boolean checkDuplicate(int[] a, int n) {
5
        int lastIndex = n - 1;
6
        builedMaxHeap(a,lastIndex);
7
        while(lastIndex > 0){
8
            swap(a,0,lastIndex);
9
            if(--lastIndex == 0){//如果只剩一個元素,就不用重新建堆了,排序結束
10
                break;
11
            }
12
            adjustHeap(a,0,lastIndex);
13
        }
14
 
                        
15
        for(int i = 0; i < n-1; i++){
16
            if(a[i] == a[i+1])
17
                return true;
18
        }
19
        return false;
20
    }
21
 
                        
22
 
                        
23
 
                        
24
    public void builedMaxHeap(int[] arr, int lastIndex) {
25
        //從最后一個元素的父元素開始構建最大堆
26
        int j = (lastIndex - 1)/2;
27
        while(j >= 0){
28
            int rootIndex = j;
29
            adjustHeap(arr,rootIndex,lastIndex);
30
            j--;
31
        }
32
    }
33
 
                        
34
    public void adjustHeap(int[] arr, int rootIndex, int lastIndex) {
35
        int childNodeIndex = rootIndex * 2 + 1;
36
 
                        
37
        while(childNodeIndex <= lastIndex){//至少有一個子節點的時候,繼續循環
38
            //有右孩子,並且右孩子比左孩子大,那么childNodeIndex賦值給更大的孩子
39
            if((childNodeIndex+1) <= lastIndex && arr[childNodeIndex+1] > arr[childNodeIndex]){
40
                childNodeIndex++;
41
            }
42
            //子孩子比父親小,說明堆構建完成,跳出循環
43
            if(arr[childNodeIndex] <= arr[rootIndex]){
44
                break;
45
            }
46
            else{
47
                swap(arr, rootIndex, childNodeIndex);
48
                rootIndex = childNodeIndex;
49
                childNodeIndex = childNodeIndex * 2 + 1;
50
            }
51
        }
52
    }
53
 
                        
54
    public void swap(int[] arr, int m, int n) {
55
        int temp = arr[m];
56
        arr[m] = arr[n];
57
        arr[n] = temp;
58
    }
59
}
 
 
您的代碼已保存
答案正確:恭喜!您提交的程序通過了所有的測試用例

 
 


免責聲明!

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



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