分治思想:
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);
}
}