Merge Sort based solution java easy to understand


  • 0
    C

    based on the common merge sort based solution to these kind of questions. we will need to sort index instead of actual numbers to keep track of for each index how many smaller numbers after it got sorted and put in front of them which is what reversecount means.

    class Solution {
        public List<Integer> countSmaller(int[] nums) {
            List<Integer> res = new ArrayList<Integer>();
            int[] indexes = new int[nums.length];
            
            for(int i = 0; i < nums.length; i++){
        	    indexes[i] = i;
                res.add(0);
            }
            mergesort(nums, indexes, res, 0, nums.length - 1);
            return res;
        }
        
        private void mergesort(int[] nums, int[] indexes, List<Integer> res, int start, int end){
            if (end <= start) return;
            
            int mid = start + ((end - start) >> 1);
            mergesort(nums, indexes, res, start, mid);
            mergesort(nums, indexes, res, mid+1, end);
            
            int l = start, r = mid + 1, p = 0;
            int reversecount = 0;
            int[] tmp = new int[end - start + 1];
            
            for(; l <= mid; l++, p++) {
                while(r <= end && nums[indexes[r]] < nums[indexes[l]]) {
                    tmp[p++] = indexes[r++];
                    reversecount++;
                }
                tmp[p] = indexes[l];
                res.set(indexes[l], res.get(indexes[l]) + reversecount);
            }
            
            for(int k = 0; k < p; k++) indexes[start+k] = tmp[k];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.