From 114d36fc2d81068503cae91e8d267527b4825860 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 5 Dec 2024 19:08:48 +0800 Subject: [PATCH] feat: add solutions to lc problem: No.1385 No.1385.Find the Distance Value Between Two Arrays --- .../README.md | 115 ++++++----------- .../README_EN.md | 119 +++++++----------- .../Solution.cpp | 15 ++- .../Solution.go | 8 +- .../Solution.java | 21 +--- .../Solution.py | 10 +- .../Solution.rs | 27 ++-- .../Solution.ts | 20 +-- 8 files changed, 118 insertions(+), 217 deletions(-) diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md index 8b3ab47cb18e6..d3ae26f6f0d1c 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md @@ -33,16 +33,16 @@ tags: 输出:2 解释: 对于 arr1[0]=4 我们有: -|4-10|=6 > d=2 -|4-9|=5 > d=2 -|4-1|=3 > d=2 -|4-8|=4 > d=2 +|4-10|=6 > d=2 +|4-9|=5 > d=2 +|4-1|=3 > d=2 +|4-8|=4 > d=2 所以 arr1[0]=4 符合距离要求 对于 arr1[1]=5 我们有: -|5-10|=5 > d=2 -|5-9|=4 > d=2 -|5-1|=4 > d=2 +|5-10|=5 > d=2 +|5-9|=4 > d=2 +|5-1|=4 > d=2 |5-8|=3 > d=2 所以 arr1[1]=5 也符合距离要求 @@ -51,7 +51,7 @@ tags: |8-9|=1 <= d=2 |8-1|=7 > d=2 |8-8|=0 <= d=2 -存在距离小于等于 2 的情况,不符合距离要求 +存在距离小于等于 2 的情况,不符合距离要求 故而只有 arr1[0]=4 和 arr1[1]=5 两个符合距离要求,距离值为 2 @@ -85,9 +85,9 @@ tags: ### 方法一:排序 + 二分查找 -我们可以先对数组 $arr2$ 排序,然后对于数组 $arr1$ 中的每个元素 $a$,使用二分查找,找到数组 $arr2$ 中第一个大于等于 $a-d$ 的元素,如果元素存在,且小于等于 $a+d$,则说明不符合距离要求,否则说明符合距离要求。我们将符合距离要求的元素个数累加,即为答案。 +我们可以先对数组 $\textit{arr2}$ 排序,然后对于数组 $\textit{arr1}$ 中的每个元素 $x$,使用二分查找,找到数组 $\textit{arr2}$ 中第一个大于等于 $x - d$ 的元素,如果元素存在,且小于等于 $x + d$,则说明不符合距离要求,否则说明符合距离要求。我们将符合距离要求的元素个数累加,即为答案。 -时间复杂度 $O((m + n) \times \log n)$,空间复杂度 $O(\log n)$。其中 $m$ 和 $n$ 分别是数组 $arr1$ 和 $arr2$ 的长度。 +时间复杂度 $O((m + n) \times \log n)$,空间复杂度 $O(\log n)$。其中 $m$ 和 $n$ 分别是数组 $\textit{arr1}$ 和 $\textit{arr2}$ 的长度。 @@ -96,12 +96,12 @@ tags: ```python class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: - def check(a: int) -> bool: - i = bisect_left(arr2, a - d) - return i == len(arr2) or arr2[i] > a + d - arr2.sort() - return sum(check(a) for a in arr1) + ans = 0 + for x in arr1: + i = bisect_left(arr2, x - d) + ans += i == len(arr2) or arr2[i] > x + d + return ans ``` #### Java @@ -111,26 +111,15 @@ class Solution { public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { Arrays.sort(arr2); int ans = 0; - for (int a : arr1) { - if (check(arr2, a, d)) { + for (int x : arr1) { + int i = Arrays.binarySearch(arr2, x - d); + i = i < 0 ? -i - 1 : i; + if (i == arr2.length || arr2[i] > x + d) { ++ans; } } return ans; } - - private boolean check(int[] arr, int a, int d) { - int l = 0, r = arr.length; - while (l < r) { - int mid = (l + r) >> 1; - if (arr[mid] >= a - d) { - r = mid; - } else { - l = mid + 1; - } - } - return l >= arr.length || arr[l] > a + d; - } } ``` @@ -140,14 +129,13 @@ class Solution { class Solution { public: int findTheDistanceValue(vector& arr1, vector& arr2, int d) { - auto check = [&](int a) -> bool { - auto it = lower_bound(arr2.begin(), arr2.end(), a - d); - return it == arr2.end() || *it > a + d; - }; - sort(arr2.begin(), arr2.end()); + ranges::sort(arr2); int ans = 0; - for (int& a : arr1) { - ans += check(a); + for (int x : arr1) { + auto it = ranges::lower_bound(arr2, x - d); + if (it == arr2.end() || *it > x + d) { + ++ans; + } } return ans; } @@ -159,9 +147,9 @@ public: ```go func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { sort.Ints(arr2) - for _, a := range arr1 { - i := sort.SearchInts(arr2, a-d) - if i == len(arr2) || arr2[i] > a+d { + for _, x := range arr1 { + i := sort.SearchInts(arr2, x-d) + if i == len(arr2) || arr2[i] > x+d { ans++ } } @@ -173,23 +161,11 @@ func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { ```ts function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number { - const check = (a: number) => { - let l = 0; - let r = arr2.length; - while (l < r) { - const mid = (l + r) >> 1; - if (arr2[mid] >= a - d) { - r = mid; - } else { - l = mid + 1; - } - } - return l === arr2.length || arr2[l] > a + d; - }; arr2.sort((a, b) => a - b); - let ans = 0; - for (const a of arr1) { - if (check(a)) { + let ans: number = 0; + for (const x of arr1) { + const i = _.sortedIndex(arr2, x - d); + if (i === arr2.length || arr2[i] > x + d) { ++ans; } } @@ -203,26 +179,17 @@ function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number impl Solution { pub fn find_the_distance_value(arr1: Vec, mut arr2: Vec, d: i32) -> i32 { arr2.sort(); - let n = arr2.len(); - let mut res = 0; - for &num in arr1.iter() { - let mut left = 0; - let mut right = n - 1; - while left < right { - let mid = left + (right - left) / 2; - if arr2[mid] <= num { - left = mid + 1; - } else { - right = mid; - } - } - if i32::abs(num - arr2[left]) <= d || (left != 0 && i32::abs(num - arr2[left - 1]) <= d) - { - continue; + let mut ans = 0; + for &x in &arr1 { + let i = match arr2.binary_search(&(x - d)) { + Ok(j) => j, + Err(j) => j, + }; + if i == arr2.len() || arr2[i] > x + d { + ans += 1; } - res += 1; } - res + ans } } ``` diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md index a3712f51fde41..0e293c20adbdc 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md @@ -31,16 +31,16 @@ tags:
 Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
 Output: 2
-Explanation: 
-For arr1[0]=4 we have: 
-|4-10|=6 > d=2 
-|4-9|=5 > d=2 
-|4-1|=3 > d=2 
-|4-8|=4 > d=2 
-For arr1[1]=5 we have: 
-|5-10|=5 > d=2 
-|5-9|=4 > d=2 
-|5-1|=4 > d=2 
+Explanation:
+For arr1[0]=4 we have:
+|4-10|=6 > d=2
+|4-9|=5 > d=2
+|4-1|=3 > d=2
+|4-8|=4 > d=2
+For arr1[1]=5 we have:
+|5-10|=5 > d=2
+|5-9|=4 > d=2
+|5-1|=4 > d=2
 |5-8|=3 > d=2
 For arr1[2]=8 we have:
 |8-10|=2 <= d=2
@@ -80,9 +80,9 @@ For arr1[2]=8 we have:
 
 ### Solution 1: Sorting + Binary Search
 
-We can first sort the array $arr2$, then for each element $a$ in array $arr1$, use binary search to find the first element in array $arr2$ that is greater than or equal to $a-d$. If such an element exists and is less than or equal to $a+d$, it means that it does not meet the distance requirement. Otherwise, it meets the distance requirement. We accumulate the number of elements that meet the distance requirement, which is the answer.
+We can first sort the array $\textit{arr2}$, and then for each element $x$ in the array $\textit{arr1}$, use binary search to find the first element in the array $\textit{arr2}$ that is greater than or equal to $x - d$. If such an element exists and is less than or equal to $x + d$, it does not meet the distance requirement. Otherwise, it meets the distance requirement. We count the number of elements that meet the distance requirement, which is the answer.
 
-The time complexity is $O((m + n) \times \log n)$, and the space complexity is $O(\log n)$. Where $m$ and $n$ are the lengths of arrays $arr1$ and $arr2$, respectively.
+The time complexity is $O((m + n) \times \log n)$, and the space complexity is $O(\log n)$. Here, $m$ and $n$ are the lengths of the arrays $\textit{arr1}$ and $\textit{arr2}$, respectively.
 
 
 
@@ -91,12 +91,12 @@ The time complexity is $O((m + n) \times \log n)$, and the space complexity is $
 ```python
 class Solution:
     def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
-        def check(a: int) -> bool:
-            i = bisect_left(arr2, a - d)
-            return i == len(arr2) or arr2[i] > a + d
-
         arr2.sort()
-        return sum(check(a) for a in arr1)
+        ans = 0
+        for x in arr1:
+            i = bisect_left(arr2, x - d)
+            ans += i == len(arr2) or arr2[i] > x + d
+        return ans
 ```
 
 #### Java
@@ -106,26 +106,15 @@ class Solution {
     public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
         Arrays.sort(arr2);
         int ans = 0;
-        for (int a : arr1) {
-            if (check(arr2, a, d)) {
+        for (int x : arr1) {
+            int i = Arrays.binarySearch(arr2, x - d);
+            i = i < 0 ? -i - 1 : i;
+            if (i == arr2.length || arr2[i] > x + d) {
                 ++ans;
             }
         }
         return ans;
     }
-
-    private boolean check(int[] arr, int a, int d) {
-        int l = 0, r = arr.length;
-        while (l < r) {
-            int mid = (l + r) >> 1;
-            if (arr[mid] >= a - d) {
-                r = mid;
-            } else {
-                l = mid + 1;
-            }
-        }
-        return l >= arr.length || arr[l] > a + d;
-    }
 }
 ```
 
@@ -135,14 +124,13 @@ class Solution {
 class Solution {
 public:
     int findTheDistanceValue(vector& arr1, vector& arr2, int d) {
-        auto check = [&](int a) -> bool {
-            auto it = lower_bound(arr2.begin(), arr2.end(), a - d);
-            return it == arr2.end() || *it > a + d;
-        };
-        sort(arr2.begin(), arr2.end());
+        ranges::sort(arr2);
         int ans = 0;
-        for (int& a : arr1) {
-            ans += check(a);
+        for (int x : arr1) {
+            auto it = ranges::lower_bound(arr2, x - d);
+            if (it == arr2.end() || *it > x + d) {
+                ++ans;
+            }
         }
         return ans;
     }
@@ -154,9 +142,9 @@ public:
 ```go
 func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) {
 	sort.Ints(arr2)
-	for _, a := range arr1 {
-		i := sort.SearchInts(arr2, a-d)
-		if i == len(arr2) || arr2[i] > a+d {
+	for _, x := range arr1 {
+		i := sort.SearchInts(arr2, x-d)
+		if i == len(arr2) || arr2[i] > x+d {
 			ans++
 		}
 	}
@@ -168,23 +156,11 @@ func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) {
 
 ```ts
 function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number {
-    const check = (a: number) => {
-        let l = 0;
-        let r = arr2.length;
-        while (l < r) {
-            const mid = (l + r) >> 1;
-            if (arr2[mid] >= a - d) {
-                r = mid;
-            } else {
-                l = mid + 1;
-            }
-        }
-        return l === arr2.length || arr2[l] > a + d;
-    };
     arr2.sort((a, b) => a - b);
-    let ans = 0;
-    for (const a of arr1) {
-        if (check(a)) {
+    let ans: number = 0;
+    for (const x of arr1) {
+        const i = _.sortedIndex(arr2, x - d);
+        if (i === arr2.length || arr2[i] > x + d) {
             ++ans;
         }
     }
@@ -198,26 +174,17 @@ function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number
 impl Solution {
     pub fn find_the_distance_value(arr1: Vec, mut arr2: Vec, d: i32) -> i32 {
         arr2.sort();
-        let n = arr2.len();
-        let mut res = 0;
-        for &num in arr1.iter() {
-            let mut left = 0;
-            let mut right = n - 1;
-            while left < right {
-                let mid = left + (right - left) / 2;
-                if arr2[mid] <= num {
-                    left = mid + 1;
-                } else {
-                    right = mid;
-                }
-            }
-            if i32::abs(num - arr2[left]) <= d || (left != 0 && i32::abs(num - arr2[left - 1]) <= d)
-            {
-                continue;
+        let mut ans = 0;
+        for &x in &arr1 {
+            let i = match arr2.binary_search(&(x - d)) {
+                Ok(j) => j,
+                Err(j) => j,
+            };
+            if i == arr2.len() || arr2[i] > x + d {
+                ans += 1;
             }
-            res += 1;
         }
-        res
+        ans
     }
 }
 ```
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp
index e443ae16c3b8d..4cc845e655574 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.cpp	
@@ -1,15 +1,14 @@
 class Solution {
 public:
     int findTheDistanceValue(vector& arr1, vector& arr2, int d) {
-        auto check = [&](int a) -> bool {
-            auto it = lower_bound(arr2.begin(), arr2.end(), a - d);
-            return it == arr2.end() || *it > a + d;
-        };
-        sort(arr2.begin(), arr2.end());
+        ranges::sort(arr2);
         int ans = 0;
-        for (int& a : arr1) {
-            ans += check(a);
+        for (int x : arr1) {
+            auto it = ranges::lower_bound(arr2, x - d);
+            if (it == arr2.end() || *it > x + d) {
+                ++ans;
+            }
         }
         return ans;
     }
-};
\ No newline at end of file
+};
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.go b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.go
index 854343c6a8291..6df8901695633 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.go	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.go	
@@ -1,10 +1,10 @@
 func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) {
 	sort.Ints(arr2)
-	for _, a := range arr1 {
-		i := sort.SearchInts(arr2, a-d)
-		if i == len(arr2) || arr2[i] > a+d {
+	for _, x := range arr1 {
+		i := sort.SearchInts(arr2, x-d)
+		if i == len(arr2) || arr2[i] > x+d {
 			ans++
 		}
 	}
 	return
-}
\ No newline at end of file
+}
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java
index b04604fd6f020..0079e764ebb3d 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.java	
@@ -2,24 +2,13 @@ class Solution {
     public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
         Arrays.sort(arr2);
         int ans = 0;
-        for (int a : arr1) {
-            if (check(arr2, a, d)) {
+        for (int x : arr1) {
+            int i = Arrays.binarySearch(arr2, x - d);
+            i = i < 0 ? -i - 1 : i;
+            if (i == arr2.length || arr2[i] > x + d) {
                 ++ans;
             }
         }
         return ans;
     }
-
-    private boolean check(int[] arr, int a, int d) {
-        int l = 0, r = arr.length;
-        while (l < r) {
-            int mid = (l + r) >> 1;
-            if (arr[mid] >= a - d) {
-                r = mid;
-            } else {
-                l = mid + 1;
-            }
-        }
-        return l >= arr.length || arr[l] > a + d;
-    }
-}
\ No newline at end of file
+}
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py
index 8e8dccc768186..d692e173d0013 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py	
@@ -1,8 +1,8 @@
 class Solution:
     def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
-        def check(a: int) -> bool:
-            i = bisect_left(arr2, a - d)
-            return i == len(arr2) or arr2[i] > a + d
-
         arr2.sort()
-        return sum(check(a) for a in arr1)
+        ans = 0
+        for x in arr1:
+            i = bisect_left(arr2, x - d)
+            ans += i == len(arr2) or arr2[i] > x + d
+        return ans
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.rs b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.rs
index 70fa4f47fcccd..afa296a9d8414 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.rs	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.rs	
@@ -1,25 +1,16 @@
 impl Solution {
     pub fn find_the_distance_value(arr1: Vec, mut arr2: Vec, d: i32) -> i32 {
         arr2.sort();
-        let n = arr2.len();
-        let mut res = 0;
-        for &num in arr1.iter() {
-            let mut left = 0;
-            let mut right = n - 1;
-            while left < right {
-                let mid = left + (right - left) / 2;
-                if arr2[mid] <= num {
-                    left = mid + 1;
-                } else {
-                    right = mid;
-                }
+        let mut ans = 0;
+        for &x in &arr1 {
+            let i = match arr2.binary_search(&(x - d)) {
+                Ok(j) => j,
+                Err(j) => j,
+            };
+            if i == arr2.len() || arr2[i] > x + d {
+                ans += 1;
             }
-            if i32::abs(num - arr2[left]) <= d || (left != 0 && i32::abs(num - arr2[left - 1]) <= d)
-            {
-                continue;
-            }
-            res += 1;
         }
-        res
+        ans
     }
 }
diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.ts b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.ts
index 870f531732dcc..658d83c7e0e42 100644
--- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.ts	
+++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.ts	
@@ -1,21 +1,9 @@
 function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number {
-    const check = (a: number) => {
-        let l = 0;
-        let r = arr2.length;
-        while (l < r) {
-            const mid = (l + r) >> 1;
-            if (arr2[mid] >= a - d) {
-                r = mid;
-            } else {
-                l = mid + 1;
-            }
-        }
-        return l === arr2.length || arr2[l] > a + d;
-    };
     arr2.sort((a, b) => a - b);
-    let ans = 0;
-    for (const a of arr1) {
-        if (check(a)) {
+    let ans: number = 0;
+    for (const x of arr1) {
+        const i = _.sortedIndex(arr2, x - d);
+        if (i === arr2.length || arr2[i] > x + d) {
             ++ans;
         }
     }