• leetcode-剑指41-OK


    // language C with STL(C++)
    // 剑指41
    // https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
    
    
    class MedianFinder {
    public:
    	int what[25000];
        int next = 0;
        /** initialize your data structure here. */
    
        int FindPosition(int num){
        	// res 满足 what[res-1]<= num, what[res]>num,这两个数都可能不存在
        	if(what[0] > num) return 0;
        	if(what[next-1]<=num) return next;
        	int res = 1;
        	for(; res<next; res++){
        		if((what[res-1] <= num) &&(what[res]>num))
        			return res;
        	}
            // printf("(%d)",next);
            // display();
        	return -1;	// 出错
        }
    
        void display(){
            for(int i =0; i <next; i++)
                printf("%dT", what[i]);
            printf("
    ");
        }
    
        MedianFinder() {
        }
        
        void addNum(int num) {
        	// 相当于找到num所在位置index,然后index~next-1位置的数全都后移一位
        	if(next== 0){
        		what[next] = num;
                next++;
        	}else{
    	    	int position = FindPosition(num);
                // printf("%d#",position);
    	    	for(int i=next; i>position; i--){
    	    		what[i] = what[i-1];
    	    	}
    	    	what[position] = num;
    	    	next++;
    	    }
        }
        
        double findMedian() {
        	double res;
        	if(next%2 ==1)
        		res = what[next/2];
        	else{
        		// printf("%d-", what[next/2-1]);
        		// printf("%d-", what[next/2]);
        		res = what[next/2-1] + what[next/2];
                // printf("%d-", res);
                res /=2;
        	}
        	return res;
        }
    };
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder* obj = new MedianFinder();
     * obj->addNum(num);
     * double param_2 = obj->findMedian();
     */
    
  • 相关阅读:
    BZOJ 1630/2023 Ant Counting 数蚂蚁
    BZOJ 3997 组合数学
    BZOJ 2200 道路与航线
    BZOJ 3181 BROJ
    BZOJ 4011 落忆枫音
    BZOJ 4027 兔子与樱花
    vijos 1741 观光公交
    vijos 1776 关押罪犯
    vijos 1780 开车旅行
    5、异步通知机制
  • 原文地址:https://www.cnblogs.com/gallien/p/14390785.html
Copyright © 2020-2023  润新知