1460. Make Two Arrays Equal by Reversing Sub-arrays

Given two integer arrays of equal length target and arr.

In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.

Return True if you can make arr equal to target, or False otherwise.

可以任意交换任意长度子数组,考虑如果每次交换的两个子数组都是单个数,那么其实就跟排序是一样的,所以只要元素一致必定会有办法还原,因此只需要判断两个数组的元素是否完全相同。

  • target.length == arr.length
  • 1 <= target.length <= 1000
  • 1 <= target[i] <= 1000
  • 1 <= arr[i] <= 1000
class Solution(object):
    def canBeEqual(self, target, arr):
        """
        :type target: List[int]
        :type arr: List[int]
        :rtype: bool
        """
        cnt = [0] * 1001
        for value in arr:
            cnt[value] += 1
        for value in target:
            cnt[value] -= 1
        for i in range(1, 1001, 1):
            if cnt[i] != 0:
                return False
        return True

 

posted @ 2020-06-29 12:48  whatyouthink  阅读(31)  评论(0编辑  收藏  举报