美文网首页
Minimum Swaps To Make Sequences

Minimum Swaps To Make Sequences

作者: Frank_Kivi | 来源:发表于2018-06-27 21:23 被阅读4次

https://www.lintcode.com/problem/minimum-swaps-to-make-sequences-increasing/description

public class Solution {
    /**
     * @param A: an array
     * @param B: an array
     * @return: the minimum number of swaps to make both sequences strictly increasing
     */
    public int minSwap(int[] A, int[] B) {
        // Write your code here
        int s = 1;
        int n = 0;
        for (int i = 1; i < A.length; i++) {
            int s1 = Integer.MAX_VALUE;
            int n1 = Integer.MAX_VALUE;
            if (A[i] > A[i - 1] && B[i] > B[i - 1]) {
//                恰好有序,要么都交换,要么不交换
                n1 = Math.min(n, n1);
                s1 = Math.min(s1, s + 1);
            }
            if (A[i] > B[i - 1] && B[i] > A[i - 1]) {
//                可以交换
                s1 = Math.min(s1, n + 1);//这次交换
                n1 = Math.min(n1, s);//上次交换
            }
            s = s1;
            n = n1;
        }
        return Math.min(s, n);
    }
}

相关文章

网友评论

      本文标题:Minimum Swaps To Make Sequences

      本文链接:https://www.haomeiwen.com/subject/lhgiyftx.html