[关闭]
@xmruibi 2015-05-02T23:22:42.000000Z 字数 2283 阅读 769

Array Summary

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.

Content

1. Sum of Array

  1. public static int sum(int[] num, int idx) {
  2. if(idx==num.length)
  3. return 0;
  4. return num[idx]+sum(num, idx+1);
  5. }

2. Get the Max and Min of Array (Divide and Conquer)

  1. public static int[] findMaxAndMin(int[] num) {
  2. return helper(num, 0, num.length - 1);
  3. }
  4. private static int[] helper(int[] num, int l, int r) {
  5. if (l >= r)
  6. return new int[] { num[l], num[l] };
  7. if (l + 1 == r)
  8. return new int[] { Math.min(num[l], num[r]),
  9. Math.max(num[l], num[r]) };
  10. int m = l + ((r - l) >> 1);
  11. int[] resL = helper(num, l, m);
  12. int[] resR = helper(num, m + 1, r);
  13. return new int[] { Math.min(resL[0], resR[0]),
  14. Math.max(resL[1], resR[1]) };
  15. }

3. Get the Max and Second Max of Array (Divide and Conquer)

  1. public static int[] findMaxAndSecondMax(int[] num) {
  2. if (num == null || num.length == 0)
  3. return null;
  4. return helper(num, 0, num.length - 1);
  5. }
  6. private static int[] helper(int[] num, int l, int r) {
  7. if (l >= r)
  8. return new int[] { num[l], num[l] };
  9. if (l + 1 == r)
  10. return new int[] { Math.min(num[l], num[r]),
  11. Math.max(num[l], num[r]) };
  12. int m = l + ((r - l) >> 1);
  13. int[] resL = helper(num, l, m);
  14. int[] resR = helper(num, m + 1, r);
  15. int max, secondMax;
  16. if (resL[1] > resR[1]) {
  17. max = resL[1];
  18. if (resL[0] < resR[1])
  19. secondMax = resR[1];
  20. else
  21. secondMax = resL[0];
  22. } else {
  23. max = resR[1];
  24. if (resL[1] < resR[0])
  25. secondMax = resR[0];
  26. else
  27. secondMax = resL[1];
  28. }
  29. return new int[] { secondMax, max };
  30. }

4. Find Min Gap between two element in unsorted array (Time compexity: O(n))

  1. public static int findMinGap(int[] num) {
  2. if (num == null || num.length == 0)
  3. return 0;
  4. int min = Integer.MAX_VALUE;
  5. int max = Integer.MIN_VALUE;
  6. /*************** Using bucket as sort tool ***************/
  7. for (int i = 0; i < num.length; i++) {
  8. min = Math.min(min, num[i]);
  9. max = Math.max(max, num[i]);
  10. }
  11. // set a bucket array with length of range
  12. int range = max - min;
  13. int[] bucket = new int[range + 1];
  14. for (int i = 0; i < num.length; i++)
  15. bucket[num[i] - min]++;
  16. // return to original array!!
  17. int idx = 0;
  18. for (int i = 0; i < bucket.length; i++)
  19. while (bucket[i] > 0) {
  20. num[idx++] = i;
  21. bucket[i]--;
  22. }
  23. /************ End of Sort! ************/
  24. int minGap = Integer.MAX_VALUE;
  25. for (int i = 1; i < num.length; i++)
  26. minGap = Math.min(minGap, num[i] - num[i - 1]);
  27. return minGap;
  28. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注