There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs.
For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on…
Return the minimum cost to paint all houses.
Example 1:
Input: costs = [[17,2,17],[16,16,5],[14,3,19]] Output: 10 Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10.
Example 2:
Input: costs = [[7,6,2]] Output: 2
Constraints:costs.length == n costs[i].length == 31 <= n <= 100 * 1 <= costs[i][j] <= 20
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.
`1 <= wordsDict.length <= 3 104*1 <= wordsDict[i].length <= 10*wordsDict[i]consists of lowercase English letters.
*word1andword2are inwordsDict.
*word1 != word2`
题目大意:
求单词列表中给定的两个单词的最短下标距离
解题思路:
同向双指针
解题步骤:
N/A
注意事项:
同向双指针,分别指向两单词,计算结果时必须是找到才比较
Python代码:
1 2 3 4 5 6 7 8 9 10 11
defshortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: p1 = p2 = -1 res = float('inf') for i, word in enumerate(wordsDict): if word == word1: p1 = i if word == word2: p2 = i if p1 != -1and p2 != -1: res = min(res, abs(p1 - p2)) return res