leetcoder 115(未解决)

思路:

  1. 左右分别从大到小归并排序
  2. 将他们总体排序的时候,如果左边的数大于右边的数,small[p1]=small[p1]+R-p2+1

还需要建立一个索引,来记录原来的位置

public List countSmaller(int[] nums) {
        List list = new ArrayList<>();
        if(nums == null || nums.length == 0)
            return list;
      
        int[] small = new int[nums.length];
        sort(nums, small, 0, nums.length-1);
        for(int i : small)
            list.add(i);
        return list;
    }
    public static void sort(int[] nums,int[] small, int L, int R){
        if(L==R)
            return;
        int mid = L + ((R - L) >> 1);
        sort(nums, small, L, mid);
        sort(nums, small, mid + 1, R);
        merge(nums, small, L, mid, R);
    }
    public static void merge(int[] nums, int[] small, int L, int mid, int R){
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = mid + 1;
        while (p1 <= mid && p2 <= R){
            small[p1] = nums[p1] > nums[p2] ? ++small[p1] : small[p1];

            help[i++] = nums[p1] > nums[p2] ? nums[p1++] : nums[p2++];
        }
        //将剩下的数装入数组中,和归并排序一样
        while (p1 <= mid){
            help[i++] = nums[p1++];
        }
        while (p2 <= R){
            help[i++] = nums[p2++];
        }
        
        //将help数组复制给nums
        for(int j = 0; j < help.length; j++)
            nums[j] = help[j];

    }

你可能感兴趣的:(leetcode)