Given two integer arrays
The distance value is defined as the number of elements
arr1 and arr2, and the integer d, return the distance value between the two arrays.The distance value is defined as the number of elements
arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2Approach
Java
public class FindDistanceValueTwoArrays {public static void main(String[] args) {int[] arr1 = { 4, 5, 8 };int[] arr2 = { 10, 9, 1, 8 };int d = 2;System.out.println(findTheDistanceValue(arr1, arr2, d));}static int findTheDistanceValue(int[] arr1, int[] arr2, int d) {int n = arr1.length, m = arr2.length;int cnt = 0;for (int i = 0; i < n; i++) {int j;int flag = 1;for (j = 0; j < m; j++) {if (Math.abs(arr1[i] - arr2[j]) <= d) {flag = 0;break;}}cnt += flag;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int findTheDistanceValue(vector<int> &arr1, vector<int> &arr2, int d){int n = arr1.size(), m = arr2.size();int cnt = 0;for (int i = 0; i < n; i++){int j;int flag = 1;for (j = 0; j < m; j++){if (abs(arr1[i] - arr2[j]) <= d){flag = 0;break;}}cnt += flag;}return cnt;}int main(){vector<int> arr1 = {4, 5, 8};vector<int> arr2 = {10, 9, 1, 8};int d = 2;cout << findTheDistanceValue(arr1, arr2, d);return 0;}
No comments:
Post a Comment