數組

  1. public class Solution{  
  2.       
  3.     class SegmentTreeNode{  
  4.       public int start,end;  
  5.       public int count;  
  6.       public SegmentTreeNode left,right;  
  7.       public SegmentTreeNode(int short,int end,int count){  
  8.        this.start =start;  
  9.        this.end =end;  
  10.        this.count =count;  
  11.        this.left =this.right =null;  
  12.       }  
  13. }  
  14. SegmentTreeNode root;  
  15. public SegmentTreeNode build(int start,int end){  
  16.     if(start>end){  
  17.         return null;  
  18.     }  
  19.   
  20.   SegmentTreeNode root =new SegmentTreeNode(start,end,0);  
  21.     if(start!=end){  
  22.         int mid =(start+end)/2;  
  23.         root.left =build(start,mid);  
  24.         root.right =build(mid+1,end);  
  25.     } else{  
  26.         root.count =0;  
  27.     }  
  28.     return root;  
  29. }  
  30. public int querySegmentTree(SegmentTreeNode root,int start,int end){  
  31.     if(start==root.start&&root.end==end){  
  32.         return root.count;  
  33.     }  
  34.     int mid =(count.start+root.end)/2;  
  35.     int leftcount =0,rightcount =0  
  36.     //左子區  
  37.     if(start<=mid){  
  38.         if(mid<end){  
  39.             leftcount =querySegmentTree(root.left,start,mid);  
  40.         }else{  
  41.             leftcount =querySegmentTree(root.left,start,end);  
  42.         }  
  43.     }  
  44.     //右子區  
  45.     if(mid<end){  
  46.         if(start<=mid){  
  47.             rightcount =querySegmentTree(root.right,mid+1,end);  
  48.         }else{  
  49.             rightcount =querySegmentTree(root.right,start,end);  
  50.         }  
  51.     }  
  52.     //else就是不相交  
  53.     return leftcount+rightcount;   
  54.       
  55. }  
  56. public void modifySegmeniTree(SegmentTreeNode root,int index,int value){  
  57.     if(root.start ==index&&root.end==index){  
  58.         root.count+=value;  
  59.         return;  
  60.     }  
  61.     //查詢  
  62.     int mid =(root.start+root.end)/2;  
  63.     if(root.start<=index&&index<=mid){  
  64.         modifySegmeniTree(root.left,index,value);  
  65.     }  
  66.     if(mid<index&&index<=root.end){  
  67.         modifySegmeniTree(root.right,index,value);  
  68.     }  
  69.     //更新  
  70.     root.count==root.left.count+root.right.count;  
  71. }  
  72. public ArrayList<Integer> countOfSmallerNumberII(int []A){  
  73.     root =build(0,10000);  
  74.     ArrayList<Integer>ans =new ArrayList<Integer>();  
  75.     int res;  
  76.     for(int i=0;i<A,length;i++){  
  77.         res=0;  
  78.     if(A[i]>0){  
  79.         res=querySegmentTree(root,0,A[i]-1);  
  80.     }  
  81.     modifySegmeniTree(root,A[i],1);  
  82.     ans.add(res);  
  83.     }  
  84.    return ans;  
  85.   }  
  86. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章