簡體   English   中英

返回兩個不同的 arrays 中的兩個元素相差 2 或更少但不相等的次數的計數

[英]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

當我在編碼 bat 上練習 Java 問題時,我遇到了以下問題陳述。

問題:-

給定兩個長度相同的 arrays 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;
}

我的問題:-

雖然我已經解決了這個問題,但我的解決方案看起來有點長。 所以我正在尋找一些比我的代碼行更少的更短、更准確的解決方案。 你能幫我解決這個問題嗎?

比較時使用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();

不使用 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;
}

該解決方案通過了CodingBat上的所有測試:

public int matchUp(int[] nums1, int[] nums2) {
  int counter = 0;
  int difference = 0;
  
   for (int i = 0; i < nums1.length; i++) {
     if (nums1[i] != nums2[i]) {
       difference = Math.abs(nums1[i] - nums2[i]);
       if (difference <= 2) {
         counter++;
       }
     }
   }
  
  return counter;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM