一些编程快速的辅助函数

1.数字反转

static int r(int n) {
        int m=0;        
        while(n!=0) {
            m = m * 10 + n % 10;
            n = n / 10; 
        }
        return m;
    }

 2.找两个排序数组的中位数

public static double findMidByCounter(int[] a, int[] b) {  
        int ai = 0, bi = 0;  
        int lena=a.length,lenb=b.length;
        int k=(lena+lenb)/2+1;
        double mid = 0;
        double midafter=0;
        while (ai < a.length && bi < b.length && k > 0) {
            mid=midafter;
            midafter = (a[ai] < b[bi]) ? a[ai++] : b[bi++];  
            k--;  
        }  
        while (ai < a.length && k > 0) { 
            mid=midafter;
            midafter = a[ai++];  
            k--;  
        }  
        while (bi < b.length && k > 0) {  
            mid=midafter;
            midafter = b[bi++];  
            k--;  
        }  
        return (lena+lenb)%2==0?(mid+midafter)/2:midafter;  
    }

 3.有序数组旋转找最小值(直接搜索效率不高,采用2分法)

1,2,3,4,5->4,5,1,2,3

public int minNumberInRotateArray(int [] array) {
        int low = 0 ; int high = array.length - 1;   
        while(low < high){
            int mid = low + (high - low) / 2;        
            if(array[mid] > array[high]){
                low = mid + 1;
            }else if(array[mid] == array[high]){
                high = high - 1;
            }else{
                high = mid;
            }   
        }
        return array[low];
}

 4.一个字符串向右移动n位

static void revertStr(char[] str, int from, int to){
        if(to - from < 1){
            return;
        }
        for(int i = from; i < (to + from + 1)/2;i++){
            swap(str,i,to -(i - from));
        }
    }
    
    static void swap(char[] s, int i, int j) {
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }
    static void circleLeftMove(char[] str, int start, int end, int len){
        revertStr(str, start, end-len);//前一部分逆置
        revertStr(str, end-len+1, end);//后一部分逆置
        revertStr(str, start, end);//全部逆置
    }

 

posted @ 2019-04-14 09:53  LeeJuly  阅读(207)  评论(0)    收藏  举报