My accepted c++ code in 200ms, pls give some advise,thks


  • 0
    T

    class Solution {
    public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
    int steps = ((m + n)/2.0+0.5) ;
    int offset = (m + n) % 2 == 0 ? 1 : 0 ;

        int h_a = -1 ;
        int h_b = -1 ;
        
        
        
        int h_index = 0 ; // 0代表a 1代表b
        
        while (1) {
            int tmp_a = -1 ;
            int tmp_b = -1 ;
            
            if ((m-1) > h_a)
                tmp_a = A[h_a+1] ;
            if ((n-1) > h_b)
                tmp_b = B[h_b+1] ;
            
            if (tmp_a*tmp_b>0) {
                if (tmp_a < tmp_b) {
                    h_index = 0 ;
                }else if (tmp_a > tmp_b){
                    h_index = 1 ;
                } else {
                    if (A[h_a+2] <= B[h_b+2]) {
                        h_index = 0 ;
                    } else {
                        h_index = 1 ;
                    }
                }
            } else {
                h_index = tmp_a != -1 ? 0:1;
            }
            
            
            
            if (h_index == 0) {
                h_a++ ;
            } else {
                h_b++ ;
            }
    
            if (--steps<=0) {
                break ;
            }
        }
    
        double num1,num2 ;
        if (h_index==0) {
            num1 = A[h_a] ;
        } else {
            num1 = B[h_b] ;
        }
        
        if (offset>0) {
            int tmp_a = -1 ;
            int tmp_b = -1 ;
            
            if ((m-1) > h_a)
                tmp_a = A[h_a+1] ;
            if ((n-1) > h_b)
                tmp_b = B[h_b+1] ;
            
            if (tmp_a*tmp_b>0) {
                if (tmp_a < tmp_b) {
                    h_index = 0 ;
                }else if (tmp_a > tmp_b){
                    h_index = 1 ;
                } else {
                    if (A[h_a+2] <= B[h_b+2]) {
                        h_index = 0 ;
                    } else {
                        h_index = 1 ;
                    }
                }
            } else {
                h_index = tmp_a != -1 ? 0:1;
            }
            
            if (h_index == 0) {
                h_a++ ;
            } else {
                h_b++ ;
            }
            
            if (h_index==0) {
                num2 = A[h_a] ;
            } else {
                num2 = B[h_b] ;
            }
            
            double sum = (num1 + num2)/2.0 ;
            return sum ;
        }else{
            return num1 ;
        }
                
        return 0.0 ;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.