Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
Example 1:
<pre>Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
Explanation: Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.
</pre>
defminTotalDistance(self, grid: List[List[int]]) -> int: x_coordinates, y_coordinates = [], [] for i inrange(len(grid)): for j inrange(len(grid[0])): if grid[i][j] == 1: x_coordinates.append(i) y_coordinates.append(j) x_coordinates.sort() y_coordinates.sort() res = 0 left, right = 0, len(y_coordinates) - 1 while left < right: res += y_coordinates[right] - y_coordinates[left] left += 1 right -= 1
left, right = 0, len(x_coordinates) - 1 while left < right: res += x_coordinates[right] - x_coordinates[left] left += 1 right -= 1 return res
Given an array of points where points[i] = [x<sub>i</sub>, y<sub>i</sub>] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
<pre>Input: s = "the sky is blue"
Output: "blue is sky the"
</pre>
Example 2:
<pre>Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
</pre>
Example 3:
<pre>Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
</pre>
Constraints:
1 <= s.length <= 10<sup>4</sup>
s contains English letters (upper-case and lower-case), digits, and spaces ' '.
There is at least one word in s.
**Follow-up: **If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
</div>
题目大意:
反转字符串中的单词顺序
解题思路:
N/A
解题步骤:
N/A
注意事项:
word不能为空,单词之间可能含多个空格
Python代码:
1 2 3 4
defreverseWords(self, s: str) -> str: words = s.split(' ') words_without_space = [word for word in words if word] return' '.join(words_without_space[::-1])