1. 程式人生 > 實用技巧 >leetcode-python 尋找兩個有序陣列的中位數

leetcode-python 尋找兩個有序陣列的中位數

分治思想:
Pow(x, n)

class Solution {
    public double myPow(double x, int n) {
        if (n == 0)
            return 1.0;
        else {
            double temp = myPow(x, n/2);
            if (n > 0)
                return  temp * temp * (n%2 == 1 ? x: 1);
            else
                return  temp * temp * (n%2 == -1 ? 1.0/x: 1);
        }
    }
}

最大子序列和

class Solution {
    public int maxSubArray(int[] nums) {
        return maxSubArray(nums, 0, nums.length - 1)[2];
    }

    public int[] maxSubArray(int[] nums, int l, int r) {
        // 左邊界最大值,右邊界最大值,區域性最大值,總和
        int[] result = new int[4];
        if (l != r) {
            int[] resL = maxSubArray(nums, l, l+(r-l)/2);
            int[] resR = maxSubArray(nums, l+(r-l)/2+1, r);
            result[0] = Math.max(resL[0], resL[3] + resR[0]);
            result[1] = Math.max(resR[1], resR[3] + resL[1]);
            result[2] = Math.max(Math.max(resL[2], resR[2]), resL[1] + resR[0]);
            result[3] = resL[3] + resR[3]; 
        } else {
            Arrays.fill(result, nums[l]);
        }
        return result;
    }
}

多數元素
左右眾數相同則直接返回,否則重新遍歷,比較出現的次數。

class Solution {
    private int countInRange(int[] nums, int num, int lo, int hi) {
        int count = 0;
        for (int i = lo; i <= hi; i++) {
            if (nums[i] == num) {
                count++;
            }
        }
        return count;
    }

    private int majorityElementRec(int[] nums, int lo, int hi) {
        // base case; the only element in an array of size 1 is the majority
        // element.
        if (lo == hi) {
            return nums[lo];
        }

        // recurse on left and right halves of this slice.
        int mid = (hi-lo)/2 + lo;
        int left = majorityElementRec(nums, lo, mid);
        int right = majorityElementRec(nums, mid+1, hi);

        // if the two halves agree on the majority element, return it.
        if (left == right) {
            return left;
        }

        // otherwise, count each element and return the "winner".
        int leftCount = countInRange(nums, left, lo, hi);
        int rightCount = countInRange(nums, right, lo, hi);

        return leftCount > rightCount ? left : right;
    }

    public int majorityElement(int[] nums) {
        return majorityElementRec(nums, 0, nums.length-1);
    }
}