[关闭]
@XQF 2018-03-07T22:57:12.000000Z 字数 407 阅读 761

如何用递归的方式求数组的最大元素?

数据结构与算法


有返回的递归经典之作

  1. public class Solution {
  2. public int findMax(int[] nums, int left, int max) {
  3. if (left == nums.length) {
  4. System.out.println(max);
  5. return max;
  6. }
  7. for (int i = left; i < nums.length; i++) {
  8. if (nums[i] > max) {
  9. max = nums[i];
  10. }
  11. return findMax(nums, i + 1, max);
  12. }
  13. return -1;
  14. }
  15. public static void main(String[] args) {
  16. Solution solution = new Solution();
  17. int[] nums = {1, 2, 10, 4, 5, 6, 6};
  18. System.out.println("result:" + solution.findMax(nums, 0, 0));
  19. }
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注