1. 程式人生 > >624. Maximum Distance in Arrays

624. Maximum Distance in Arrays

Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 
1: Input: [[1,2,3], [4,5], [1,2,3]] Output: 4 Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. Note: Each given array will have at least 1 number. There will be at least two non-empty arrays. The total number of the integers in all the m arrays will be in the range of [
2, 10000]. The integers in the m arrays will be in the range of [-10000, 10000]. // sol 1 : tle 123 / 124 test cases passed. class Solution { public int maxDistance(List<List<Integer>> arrays) { // brute force solution is to try all possible ways int res = 0; for(int
i = 0; i < arrays.size() - 1; i++){ for(int num1 : arrays.get(i)){ for(int j = i + 1; j < arrays.size(); j++){ for(int num2 : arrays.get(j)){ res = Math.max(res, Math.abs(num1 - num2)); } } } } return res; } } // sol 2 : find out a way, so that we don’t have to try all possible combinations to get the max 123 / 124 test cases passed. Tle , In the last approach, we didn't make use of the fact that every array in the listlist is sorted. Thus, instead of considering the distances among all the elements of all the arrays(except intra-array elements), we can consider only the distances between the first(minimum element) element of an array and the last(maximum element) element of the other arrays and find out the maximum distance from among all such distances. class Solution { public int maxDistance(List<List<Integer>> arrays) { int res = 0; // pick any two arrays and check only the first one and the last one for(int i = 0; i < arrays.size() - 1; i++){ int s1 = arrays.get(i).get(0); int e1 = arrays.get(i).get(arrays.get(i).size() - 1); for(int j = i + 1; j < arrays.size(); j++){ int s2 = arrays.get(j).get(0); int e2 = arrays.get(j).get(arrays.get(j).size() - 1); res = Math.max(res, Math.abs(s1 - e2)); res = Math.max(res, Math.abs(s2 - e1)); } } return res; } } // sol 3 : time n http://www.cnblogs.com/grandyang/p/7073343.html 用兩個變數start和end分別表示當前遍歷過的陣列中最小的首元素,和最大的尾元素,那麼每當我們遍歷到一個新的陣列時,只需計算新陣列尾元素和start絕對差,跟end和新陣列首元素的絕對差,取二者之間的較大值來更新結果res即可, class Solution { public int maxDistance(List<List<Integer>> arrays) { int start = arrays.get(0).get(0); int n = arrays.get(0).size(); int end = arrays.get(0).get(n - 1); int res = 0; for(int i = 1; i < arrays.size(); i++){ List<Integer> list = arrays.get(i); int newStart = list.get(0); int len = list.size(); int newEnd = list.get(len - 1); res = Math.max(res, Math.abs(newStart - end)); res = Math.max(res, Math.abs(newEnd - start)); end = Math.max(end, newEnd); start = Math.min(start, newStart); } return res; } }