Java implementation LeetCode 493 flip on

493. flip on

Given an array nums, if i <j and nums [i]> 2 * nums [j] we will (i, j) is called a flip important pair.

You need to return to the reversal of a given number of important array.

Example 1:

Input: [1,3,2,3,1]
Output: 2
Example 2:

Input: [2,4,3,5,1]
Output: 3
Note:

A given length of the array is not more than 50,000.
All digital inputs are in the array represents the range of 32-bit integers.

PS:
binary sort

class Solution {
      private int cnt;

    public int reversePairs(int[] nums) {
        int len = nums.length;
        sort(nums, Arrays.copyOf(nums, len), 0, len - 1);
        return cnt;
    }

    private void sort(int[] src, int[] dest, int s, int e) {
        if (s >= e) {
            return;
        }
        int mid = (s + e) >> 1;
        sort(dest, src, s, mid);
        sort(dest, src, mid + 1, e);
        merge(src, dest, s, mid, e);
    }

    private void merge(int[] src, int[] dest, int s, int mid, int e) {
        int i = s, j = mid + 1, k = s;
        while (i <= mid && j <= e) {
            if ((long) src[i] > 2 * ((long) src[j])) {
                cnt += mid - i + 1;
                j++;
            } else {
                i++;
            }
        }
        i = s;
        j = mid + 1;
        while (i <= mid && j <= e) {
            if (src[i] <= src[j]) {
                dest[k++] = src[i++];
            } else {
                dest[k++] = src[j++];
            }
        }
        while (i <= mid) {
            dest[k++] = src[i++];
        }
        while (j <= e) {
            dest[k++] = src[j++];
        }
    }
}
Released 1592 original articles · won praise 20000 + · Views 2.5 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105016758