Lintcode387 The Smallest Difference solution 題解
【題目描述】
Given two array of integers(the first array is array A, the second array is array B), now we are going to find a element in array A which is A[i], and another element in array B which is B[j], so that the difference between A[i] and B[j] (|A[i] - B[j]|) is as small as possible, return their smallest difference.
給定兩個整數陣列(第一個是陣列A,第二個是陣列B),在陣列 A 中取 A[i],陣列 B 中取 B[j],A[i] 和 B[j]兩者的差越小越好(|A[i] - B[j]|)。返回最小差。
【題目連結】
www.lintcode.com/en/problem/the-smallest-difference/
【題目解析】
題目的要求是O(nlogn)的時間複雜度,那麼就會想到two pointers的做法:
1. 首先,two pointers做法一般都用在有序陣列上,所以上來先把A和B排序;
2. 然後,將A中的element A[i]一個一個拿出來,跟B裡的比較。這裡不需要將B中的每一個element都拿來比較,其實最需要比的只是與A[i]相近的那些。由此我們可以利用有序陣列的特點,做一個二分搜尋,挑最重要的那些來比。比如,如果A[i]比B[mid]大,那麼diff有可能更小的就只能在B[mid]之後的那些數。
【參考答案】
相關文章
- 【題解】Solution Set - 「藍」題板刷
- Lintcode539 Move Zeroes solution 題解
- Lintcode22 Flatten List solution 題解
- Lintcode515 Paint House solution 題解AI
- 【題解】Solution Set - NOIP2024模擬賽4
- 【題解】Solution Set - NOIP2024模擬賽2
- 【題解】Solution Set - NOIP2024集訓Day56 雜湊雜題
- 【題解】Solution Set - NOIP2024集訓Day9 樹上問題
- 【題解】Solution Set - NOIP2024集訓Day57 字串字串
- 【題解】Solution Set - NOIP2024集訓Day26 dp
- 【題解】Solution Set - NOIP2024集訓Day52 圖論雜題2圖論
- 【題解】Solution Set - NOIP2024集訓Day55 圖論雜題3圖論
- 【題解】Solution Set - NOIP2024集訓Day71 貪心
- 【題解】Solution Set - NOIP2024集訓Day44-45 圖論圖論
- 【題解】Solution Set - NOIP2024集訓Day2 線段樹
- 【題解】Solution Set - NOIP2024集訓Day14 CDQ分治
- Dart: The World's Smallest Laptop AdapterDartAPT
- 【題解】Solution Set - NOIP2024集訓Day7 李超線段樹
- What is the difference Put and Post and Get?
- What is the difference between <%, <%=, <%# and -%> in ERB in Rails?AI
- Some difference between mysql & oracleMySqlOracle
- Lintcode208 Assignment Operator Overloading (C++ Only) solution 題解C++
- 【題解】Solution Set - NOIP2024集訓Day20 DP常⻅模型1「序列」模型
- Leetcode Kth Smallest Element in a BSTLeetCode
- sp4487-solution
- Whats the difference between the v$sql* viewsSQLView
- Difference between business area and profit center
- What is the difference between gross sales and revenue?ROS
- Difference of Revoke System Privileges and Object PrivilegesObject
- The difference between literal and label.
- What is the difference between a Homemaker and a Housewife?
- 【題解】Solution Set - NOIP2024集訓Day18 最佳化建圖
- 【題解】Solution Set - NOIP2024集訓Day22 DP常⻅模型3「區間」模型
- 【題解】Solution Set - NOIP2024集訓Day23 DP常⻅模型3「區間」模型
- LeetCode之Smallest Range I(Kotlin)LeetCodeKotlin
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- [LeetCode] 910. Smallest Range IILeetCode
- 【題解】Solution Set - NOIP2024集訓Day10 樹的直徑、重⼼、中⼼