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]之後的那些數。
【參考答案】
相關文章
- Lintcode539 Move Zeroes solution 題解
- Lintcode22 Flatten List solution 題解
- Lintcode515 Paint House solution 題解AI
- sp4487-solution
- Lintcode208 Assignment Operator Overloading (C++ Only) solution 題解C++
- Dart: The World's Smallest Laptop AdapterDartAPT
- What is the difference Put and Post and Get?
- Solution for Deepin DNS resolution errorDNSError
- What is the difference between <%, <%=, <%# and -%> in ERB in Rails?AI
- Some difference between mysql & oracleMySqlOracle
- solution-uva1594
- BI Solution Architect /Principal,Sr. Solution Architect - 高階DBA 職位
- Leetcode Kth Smallest Element in a BSTLeetCode
- Chapter 8 The Simplest Plug-in SolutionAPT
- 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.
- LeetCode之Smallest Range I(Kotlin)LeetCodeKotlin
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- difference with PerlApp 7.0 and PerlApp 6.0APP
- The SQL vs NoSQL Difference: MySQL vs MongoDBMySqlMongoDB
- LeetCode 389. Find the DifferenceLeetCode
- Difference between prop and attr in different version of jqueryjQuery
- Microsoft Application Architecture Solution SummaryROSAPP
- LintCode-Maximum Subarray Difference
- What is the difference between restoring and recoveringREST
- win10怎麼禁用聯想solution center win10禁用聯想solution center如何設定Win10
- LeetCode-Kth Smallest Element in a Sorted MatrixLeetCode
- SAP IoT Seeks Better Parking with New Solution
- What is the difference between application server and web server?APPServerWeb
- Difference between sap_all and sap_new
- The main difference between Java & C++(轉載)AIJavaC++
- 【Oracle】-Difference between Instance recovery and Crash RecoveryOracle
- SAP Difference between Credit memo and subsequent debits/credits
- 【Leetcode】1081. Smallest Subsequence of Distinct CharactersLeetCode
- Leetcode - Smallest Rectangle Enclosing Black PixelsLeetCode