【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】576. Split Array
- 【Lintcode】1793. Balanced Sales Array
- Clear Code for Minimal APIAPI
- Matrix Distance
- A - Distance in Tree
- [Leetcode] Edit DistanceLeetCode
- CentOS 7 Minimal 安裝 LXQTCentOSQT
- 通俗理解.NET 6 Minimal APIsAPI
- 7.47 CLUSTER_DISTANCE
- CF1092E Minimal Diameter ForestREST
- distance(Floyd求最短路)
- POI2012ODL-Distance
- 477-Total Hamming Distance
- LeetCode 461. Hamming DistanceLeetCode
- .NET 6 Minimal API 的經驗分享API
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- 錯誤 1 error LNK2019: 無法解析的外部符號 "public: __thiscall Distance::Distance(int)" (??0Distance@@QAE@H@Z),該符...Error符號
- [LeetCode] 243. Shortest Word DistanceLeetCode
- [LeetCode] 2739. Total Distance TraveledLeetCode
- LeetCode之Shortest Distance to a Character(Kotlin)LeetCodeKotlin
- 漢明距離(Hamming distance)
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- [LeetCode] 244. Shortest Word Distance IILeetCode
- [Over-Distance] Ubuntu 24.04 LTS UpdateUbuntu
- 1046 Shortest Distance(簡單模擬)
- ABC359 G - Sum of Tree Distance
- Array.from和 Array.of
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM