- public class Solution{
- class SegmentTreeNode{
- public int start,end;
- public int count;
- public SegmentTreeNode left,right;
- public SegmentTreeNode(int short,int end,int count){
- this.start =start;
- this.end =end;
- this.count =count;
- this.left =this.right =null;
- }
- }
- SegmentTreeNode root;
- public SegmentTreeNode build(int start,int end){
- if(start>end){
- return null;
- }
- SegmentTreeNode root =new SegmentTreeNode(start,end,0);
- if(start!=end){
- int mid =(start+end)/2;
- root.left =build(start,mid);
- root.right =build(mid+1,end);
- } else{
- root.count =0;
- }
- return root;
- }
- public int querySegmentTree(SegmentTreeNode root,int start,int end){
- if(start==root.start&&root.end==end){
- return root.count;
- }
- int mid =(count.start+root.end)/2;
- int leftcount =0,rightcount =0
- //左子區
- if(start<=mid){
- if(mid<end){
- leftcount =querySegmentTree(root.left,start,mid);
- }else{
- leftcount =querySegmentTree(root.left,start,end);
- }
- }
- //右子區
- if(mid<end){
- if(start<=mid){
- rightcount =querySegmentTree(root.right,mid+1,end);
- }else{
- rightcount =querySegmentTree(root.right,start,end);
- }
- }
- //else就是不相交
- return leftcount+rightcount;
- }
- public void modifySegmeniTree(SegmentTreeNode root,int index,int value){
- if(root.start ==index&&root.end==index){
- root.count+=value;
- return;
- }
- //查詢
- int mid =(root.start+root.end)/2;
- if(root.start<=index&&index<=mid){
- modifySegmeniTree(root.left,index,value);
- }
- if(mid<index&&index<=root.end){
- modifySegmeniTree(root.right,index,value);
- }
- //更新
- root.count==root.left.count+root.right.count;
- }
- public ArrayList<Integer> countOfSmallerNumberII(int []A){
- root =build(0,10000);
- ArrayList<Integer>ans =new ArrayList<Integer>();
- int res;
- for(int i=0;i<A,length;i++){
- res=0;
- if(A[i]>0){
- res=querySegmentTree(root,0,A[i]-1);
- }
- modifySegmeniTree(root,A[i],1);
- ans.add(res);
- }
- return ans;
- }
- }
數組
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.