Java > Array-2 > matchUp (CodingBat Solution)

Problem:

Given 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.

matchUp({1, 2, 3}, {2, 3, 10}) → 2
matchUp({1, 2, 3}, {2, 3, 5}) → 3
matchUp({1, 2, 3}, {2, 3, 3}) → 2


Solution:

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


5 comments :

  1. This is my solution. I think yours is better.

    public int matchUp(int[] nums1, int[] nums2) {
    int count=0;
    for(int i=0;i<nums1.length && i<nums2.length;i++) {

    if(Math.abs(nums1[i]-nums2[i])<=2 && (nums1[i]!=nums2[i])) count++;

    }

    return count;
    }

    ReplyDelete
  2. This is my solution :
    public int matchUp(int[] nums1, int[] nums2) {
    int count=0;
    for(int i=0;i<nums1.length && i<nums2.length;i++){

    if(Math.abs(nums1[i]-nums2[i])<=2 && Math.abs(nums1[i]-nums2[i])!=0) count++;

    }


    return count;
    }

    ReplyDelete
  3. public int matchUp(int[] nums1, int[] nums2) {
    int count=0;
    for(int i=0;i0)){
    count++;
    }
    }return count;
    }

    ReplyDelete
  4. public int matchUp(int[] nums1, int[] nums2) {
    int count=0;
    for(int i=0;i0)){
    count++;
    }
    }return count;
    }

    ReplyDelete
  5. public int matchUp(int[] nums1, int[] nums2) {
    int count = 0;

    for(int i=0; i < nums1.length; i++){
    int temp = Math.abs(nums1[i] - nums2[i]);

    if(temp==1 || temp==2) {
    count++;
    }
    }

    return count;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact