How do I cut down on the runtime with this? I am trying to solve the problem on LeetCode and I keep running into Time Limit Exceeded. I am trying to solve 912. Sort an Array with MergeSort. Anything may be helpful.
Which line is adding to the runtime? I am unsure of where to look next. I am still a beginner at coding.
class Solution { public int[] sortArray(int[] nums) { if (nums.length <= 1){ return nums; } int midpoint = nums.length/2; int[] left = new int[midpoint]; int[] right; if(nums.length % 2 == 0){ right = new int [midpoint]; } else { right = new int[midpoint + 1]; } for (int i=0; i < midpoint; i++){ left[i] = nums[i]; } for (int j=0; j < right.length; j++){ right[j] = nums[midpoint+j]; } int[] result = new int[nums.length]; left = sortArray(left); right = sortArray(right); result = merge(left, right); return result; } public static int[] merge(int[] left, int[] right){ int[] result = new int[left.length + right.length]; int leftPointer, rightPointer, resultPointer; leftPointer = rightPointer = resultPointer = 0; while(leftPointer < left.length || rightPointer < right.length){ if(leftPointer < left.length && rightPointer < right.length){ if(left[leftPointer] < right[rightPointer]){ result[resultPointer+1] = left[leftPointer+1]; } else { result[resultPointer++] = right[rightPointer++]; } } else if (leftPointer < left.length) { result[resultPointer++] = left[leftPointer++]; } else if(rightPointer < right.length){ result[resultPointer++] = right[rightPointer++]; } } return result; } }
https://stackoverflow.com/questions/67327297/time-limit-exceeded-trying-to-solve-leetcode-problem-mergesort-array-list April 30, 2021 at 10:06AM
没有评论:
发表评论