Codewars 解题报告:Are they the “same“?

Codewars 解题报告:Are they the "same"?

题目内容

我的解决方案

cpp 复制代码
#include <vector>

class Same {
public :
    static bool comp(std::vector<int>&a, std::vector<int>&b) {
      if ((0 == a.size() ^ 0 == b.size()))
        return false;
      if (a.size() != b.size())
        return false;
      for (int& i : a)
        i *= i;
      sort(a.begin(), a.end());
      sort(b.begin(), b.end());
      int n = (int)a.size();
      for (int i = 0; i < n; ++i)
        if (a[i] != b[i])
          return false;
      return true;
    }
};

心得

这题是真的,有点迷一开始。我陷入了一个误区,因为下面这句话:

comp(a,b) returns false because in b 132 is not the square of any number of a.

说的是:"132不是数组a中任意一个元素的平方"。那么,反过来,是不是a中任意一个元素,它的平方不在b中就返回false了呢?为了实现这一点,我用set存储了数组a和b的元素,毕竟重复的元素是没有比较的意义的!

这就是一个误区,但是从题目中看不到这个误区!我也是参考了别人的解决方案,比如:

java 复制代码
import java.util.Arrays;

public class AreSame {
  public static boolean comp(final int[] a, final int[] b) {
    return a != null && b != null && a.length == b.length && Arrays.equals(Arrays.stream(a).map(i -> i * i).sorted().toArray(), Arrays.stream(b).sorted().toArray());
  }
}

我就开始纳闷, 可能是我忽略了重复。难道在数组b中找到一个元素是a中某一个元素的平方后,这俩数就不可以再使用了吗???但是谁叫人家是对的,我就把我的代码改成了:

cpp 复制代码
#include <vector>

class Same {
public :
    static bool comp(std::vector<int>&a, std::vector<int>&b) {
      if ((0 == a.size() ^ 0 == b.size()))
        return false;
      if (a.size() != b.size())
        return false;
      for (int& i : a)
        i *= i;
      sort(a.begin(), a.end());
      sort(b.begin(), b.end());
      int n = (int)a.size();
      for (int i = 0; i < n; ++i)
        if (a[i] != b[i])
          return false;
      return true;
    }
};

英语不好,如果发现我忽略了哪一点,请指出,谢谢!