原题:
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].
Solution:
思路:由于每个数组内部都是递增的,所以只需考虑数组的首尾。为了减少复杂度,设置两个更新变量即为首的最小值(min_first)(这个最小指的是相减前面数的最小),尾的最大值(max_last),迭代更新这两个变量。但是不是单纯的max_last-min_first,因为数组内部不能相减,所以在一开始需要更新res。
class Solution(object):
def maxDistance(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: int
"""
len_arrays=len(arrays)
res=0
min_first=arrays[0][0]
max_last=arrays[0][len(arrays[0])-1]
for i in range(1,len_arrays):
array_i=arrays[i]
res=max(abs(array_i[len(array_i)-1]-min_first),abs(array_i[0]-max_last),res)
min_first=min(array_i[0],min_first)
max_last=max(array_i[len(array_i)-1],max_last)
return res
下面这种做法:
这种做法如果用C++写,在LeetCode可以通过,但是python是无法通过的,出现Time Limit Exceeded。这是由于python本身来讲较C++效率低,所以用python做算法更考验算法能力。
def maxDistance(arrays):
len_arrays=len(arrays)
maxd=0
for i in range(len_arrays-1):
isize=len(arrays[i])
for j in range(i+1,len_arrays):
jsize=len(arrays[j])
s1=abs(arrays[j][jsize-1]-arrays[i][0])
s2=abs(arrays[j][0]-arrays[i][isize-1])
s=max([s1,s2])
if s>maxd:
maxd=s
return maxd
思路:就是分别循环遍历真是最容易想到的,但是时间复杂度O(n^2)。