Loading

leetcode-1460. 通过翻转子数组使两个数组相等

1460. 通过翻转子数组使两个数组相等

图床:blogimg/刷题记录/leetcode/1460/

刷题代码汇总:https://www.cnblogs.com/geaming/p/16428234.html

题目

image-20220824145451399

思路

首先,这是一道“简单”的题,其次这是一道“简单”题。(hhh,主要是我一开始也没想到实际上很简单,主要是思路。

在一个数组arr中,如果可以选择arr的任意非空子数组并将其翻转,则我们可以知道,经过多次这样的操作可以互换任意两个位置的数字,而其他位置的数字不变。

例如:image-20220824152952525

故,对于两个序列arr我们只需要统计出现的元素及元素的个数是否相同即可。

解法

通过hash表来进行判断。

C++:unsorted_map无序映射

这个方法的空间和时间耗费比较高,没有直接排序后进行比较快。

class Solution {
public:
    bool canBeEqual(vector<int>& target, vector<int>& arr) {
        unordered_map<int,int>count1,count2;
        //计数
        for (int num:target){
            count1[num]++;
        }
        for (int num:arr){
            count2[num]++;
        }
        //比较两个序列
        if(count1.size()!=count2.size()){
            return false;
        }
        for(auto &[key,value]:count1){
            if(!count1.count(key)||count2[key]!=value){
                return false;
            }
        }
        return true;
    }
};

Python:使用Counter类

class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        return Counter(target) == Counter(arr)

排序

C++:

class Solution {
public:
    bool canBeEqual(vector<int>& target, vector<int>& arr) {
        sort(target.begin(),target.end());
        sort(arr.begin(),arr.end());
        return target==arr;
    }
};

Python:

class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        return sorted(target) == sorted(arr)

补充

posted @ 2022-08-24 21:27  Geaming  阅读(17)  评论(0编辑  收藏  举报