@xmruibi
2015-05-02T23:22:42.000000Z
字数 2283
阅读 769
Algorithm
Array is the basic data structure. Here are some popular algorithm question for array. I've tried some different way (Divide and Conquer or Recursion) to solve these problems.
public static int sum(int[] num, int idx) {if(idx==num.length)return 0;return num[idx]+sum(num, idx+1);}
public static int[] findMaxAndMin(int[] num) {return helper(num, 0, num.length - 1);}private static int[] helper(int[] num, int l, int r) {if (l >= r)return new int[] { num[l], num[l] };if (l + 1 == r)return new int[] { Math.min(num[l], num[r]),Math.max(num[l], num[r]) };int m = l + ((r - l) >> 1);int[] resL = helper(num, l, m);int[] resR = helper(num, m + 1, r);return new int[] { Math.min(resL[0], resR[0]),Math.max(resL[1], resR[1]) };}
public static int[] findMaxAndSecondMax(int[] num) {if (num == null || num.length == 0)return null;return helper(num, 0, num.length - 1);}private static int[] helper(int[] num, int l, int r) {if (l >= r)return new int[] { num[l], num[l] };if (l + 1 == r)return new int[] { Math.min(num[l], num[r]),Math.max(num[l], num[r]) };int m = l + ((r - l) >> 1);int[] resL = helper(num, l, m);int[] resR = helper(num, m + 1, r);int max, secondMax;if (resL[1] > resR[1]) {max = resL[1];if (resL[0] < resR[1])secondMax = resR[1];elsesecondMax = resL[0];} else {max = resR[1];if (resL[1] < resR[0])secondMax = resR[0];elsesecondMax = resL[1];}return new int[] { secondMax, max };}
public static int findMinGap(int[] num) {if (num == null || num.length == 0)return 0;int min = Integer.MAX_VALUE;int max = Integer.MIN_VALUE;/*************** Using bucket as sort tool ***************/for (int i = 0; i < num.length; i++) {min = Math.min(min, num[i]);max = Math.max(max, num[i]);}// set a bucket array with length of rangeint range = max - min;int[] bucket = new int[range + 1];for (int i = 0; i < num.length; i++)bucket[num[i] - min]++;// return to original array!!int idx = 0;for (int i = 0; i < bucket.length; i++)while (bucket[i] > 0) {num[idx++] = i;bucket[i]--;}/************ End of Sort! ************/int minGap = Integer.MAX_VALUE;for (int i = 1; i < num.length; i++)minGap = Math.min(minGap, num[i] - num[i - 1]);return minGap;}