【问题标题】:Return the count of the number of times that the two elements in two different arrays differ by 2 or less, but are not equal返回两个不同数组中的两个元素相差 2 或更少但不相等的次数的计数
【发布时间】:2020-10-16 10:01:11
【问题描述】:

当我在 bat 编码上练习 Java 问题时,我遇到了以下问题陈述。

问题:-

给定两个长度相同的数组 nums1 和 nums2,对于 nums1,考虑nums2中对应的元素(同时 指数)。返回两个元素的次数 相差 2 或更少,但不相等。

例子:-

matchUp([1, 2, 3], [2, 3, 10]) → 2
matchUp([1, 2, 3], [2, 3, 5]) → 3
matchUp([1, 2, 3], [2, 3, 3]) → 2

我的解决方案:-

public int matchUp(int[] nums1, int[] nums2) {
  int count=0;
  for(int i=0;i<=nums1.length-1;i++){
    if((nums1[i]-nums2[i]==1)||(nums1[i]-nums2[i]==2)||(nums2[i]-nums1[i]==1)||(nums2[i]-nums1[i]==2))
    count++;
  }
  return count;
}

我的问题:-

虽然我已经解决了这个问题,但我的解决方案看起来有点长。所以我正在寻找一些比我的代码行更少的更短更准确的解决方案。你能帮我解决这个问题吗?

【问题讨论】:

    标签: java arrays if-statement operators


    【解决方案1】:

    不使用 API,只是对@Eklavya 给出的令人惊叹的答案的补充

    public static int matchUp(int a[], int b[]){
        int count = 0;
        for(int i=0;i<a.length;i++){
            int diff = Math.abs(a[i]-b[i]);
            if(diff>0 && diff<=2)
               count++;
        }
        return count;
    }
    

    【讨论】:

      【解决方案2】:

      比较时使用Math.abs获取差异

      您可以使用 Stream API

      return IntStream.range(0, nums1.length).map(i -> Math.abs(nums1[i]-nums2[i]))
                      .filter(i -> i==2 ||i ==1).count();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        相关资源
        最近更新 更多