【Lintcode】1623. Minimal Distance In The Array
題目地址:
https://www.lintcode.com/problem/minimal-distance-in-the-array/description
給定兩個陣列 A A A和 B B B,要求返回一個與 B B B同長的陣列 C C C,使得 C [ i ] C[i] C[i]是 A A A中離 B [ i ] B[i] B[i]最近的數字。如果答案不唯一,則返回較小的那個。
思路是排序 + 二分。先對 A A A排序,然後對每個 B [ i ] B[i] B[i]找到距離其最近的數,可以先用二分找到比它小的最大的數,比如說是 A [ k ] A[k] A[k],再比較一下 A [ k + 1 ] A[k+1] A[k+1]是不是離得更近。程式碼如下:
import java.util.Arrays;
public class Solution {
/**
* @param a: array a
* @param b: the query array
* @return: Output an array of length `b.length` to represent the answer
*/
public int[] minimalDistance(int[] a, int[] b) {
// Write your code here
int[] res = new int[b.length];
Arrays.sort(a);
for (int i = 0; i < b.length; i++) {
res[i] = binarySearch(a, b[i]);
}
return res;
}
private int binarySearch(int[] a, int target) {
int l = 0, r = a.length - 1;
while (l < r) {
int m = l + (r - l + 1 >> 1);
if (a[m] <= target) {
l = m;
} else {
r = m - 1;
}
}
// 如果a[l + 1]離得更近則返回a[l + 1],否則返回a[l]
if (l + 1 < a.length && a[l + 1] - target < target - a[l]) {
return a[l + 1];
} else {
return a[l];
}
}
}
時間複雜度 O ( ( l A + l B ) log l A ) O((l_A+l_B)\log l_A) O((lA+lB)loglA),空間 O ( 1 ) O(1) O(1)。
相關文章
- LintCode-Partition Array
- 【Lintcode】576. Split Array
- 【Lintcode】1793. Balanced Sales Array
- Matrix Distance
- Clear Code for Minimal APIAPI
- CentOS 7 Minimal 安裝 LXQTCentOSQT
- 通俗理解.NET 6 Minimal APIsAPI
- [Leetcode] Edit DistanceLeetCode
- Leetcode Edit DistanceLeetCode
- array new 與 array deletedelete
- PHP array_flip() array_merge() array+array的使用總結PHP
- .NET 6 Minimal API 的經驗分享API
- Leetcode-Edit DistanceLeetCode
- Edit Distance leetcode javaLeetCodeJava
- Array()與Array.of()方法區別
- CentOS 7.3 minimal 開啟網路服務CentOS
- rhel6.6 minimal安裝ssh不能用
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- Leetcode-One Edit DistanceLeetCode
- LeetCode-Shortest Word DistanceLeetCode
- [Over-Distance] Ubuntu 24.04 LTS UpdateUbuntu
- 漢明距離(Hamming distance)
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- 錯誤 1 error LNK2019: 無法解析的外部符號 "public: __thiscall Distance::Distance(int)" (??0Distance@@QAE@H@Z),該符...Error符號
- array_filter ()、array_map ()、array_walk () 區別?容易記混淆!!!Filter
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- CF1092E Minimal Diameter ForestREST
- 【Error】centos7 minimal connect: Network is unreachableErrorCentOS
- Array物件物件
- Array Repetition
- Unique Array
- [LeetCode] 243. Shortest Word DistanceLeetCode
- LeetCode 461. Hamming DistanceLeetCode
- LeetCode-Shortest Word Distance IILeetCode
- LeetCode-Shortest Word Distance IIILeetCode