简体   繁体   中英

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

While I was practicing Java problems on coding bat I came across the following problem statement.

Problem:-

Given two arrays nums1 and nums2 of the same length, for every element in nums1, consider the corresponding element in nums2 (at the same index). Return the count of the number of times that the two elements differ by 2 or less, but are not equal.

Example:-

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

My Solution:-

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;
}

My Question:-

Though I have solved this question, my solution looks a bit long. So I am looking for some shorter and accurate solutions with fewer lines of code than mine. Can you help me with this?

Use Math.abs to get difference when compare

You can use Stream API

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

Without using API, Just an additional answer to the amazing one given by @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;
}

This solution passes all the tests on 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM