You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example 1:
Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.
Example 2:
Input: n = 1, bad = 1 Output: 1
Constraints:
* 1 <= bad <= n <= 2<sup>31</sup> - 1
算法思路:
N/A
注意事项:
题目是先good再bad,所以用first position模板
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
deffirstBadVersion(self, n): start, end = 0, n while start + 1 < end: mid = start + (end - start) // 2 if isBadVersion(mid): end = mid else: start = mid if isBadVersion(start): return start if isBadVersion(end): return end return -1
Given a pattern and a string s, return trueifsmatches thepattern.
A string smatches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.
Example 1:
Input: pattern = “abab”, s = “redblueredblue” Output: true Explanation: One possible mapping is as follows: ‘a’ -> “red” ‘b’ -> “blue”
Example 2:
Input: pattern = “aaaa”, s = “asdasdasdasd” Output: true Explanation: One possible mapping is as follows: ‘a’ -> “asd”
Example 3:
Input: pattern = “abab”, s = “asdasdasdasd” Output: true Explanation: One possible mapping is as follows: ‘a’ -> “a” ‘b’ -> “sdasd” Note that ‘a’ and ‘b’ cannot both map to “asd” since the mapping is a bijection.
Example 4:
Input: pattern = “aabb”, s = “xyzabcxzyabc” Output: false
Constraints:
1 <= pattern.length, s.length <= 20pattern and s consist of only lower-case English letters.
算法思路:
类似于word break,但由于要存储处理过map和set,DP不能处理,所以只能用DFS
注意事项:
比较映射,用Map比较A->B的映射,如已有a->dog, 另一对映射a->cat通过查找Map知道不合法。B->A的映射可通过将map的所有value存到一个set中知道。如a->dog, b->dog. b不在Map中但b对应的dog在set中,不合法。 DFS的API为dfs(pattern, word, pattern_to_word, used_set)
RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in averageO(1) time complexity.
Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
Constraints:
-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1 At most 2 * ``10<sup>5</sup> calls will be made to insert, remove, and getRandom. There will be *at least one element in the data structure when getRandom is called.
definsert(self, val: int) -> bool: if val inself.key_to_index: returnFalse self.nums.append(val) self.key_to_index[val] = len(self.nums) - 1 returnTrue
defremove(self, val: int) -> bool: if val notinself.key_to_index: returnFalse index = self.key_to_index[val] last_val = self.nums[len(self.nums) - 1] self.nums[index] = last_val self.key_to_index[last_val] = index self.key_to_index.pop(val) # remember to put it last self.nums.pop() returnTrue
Given a string s containing only three types of characters: '(', ')' and '*', return trueifsis valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
defcheckValidString(self, s: str) -> bool: stack_left, stack_star = [], [] for i inrange(len(s)): if s[i] == '(': stack_left.append(i) if s[i] == '*': stack_star.append(i) if s[i] == ')': if stack_left: # match ( first rather than * because * can be empty stack_left.pop() elif stack_star: stack_star.pop() else: returnFalse while stack_left and stack_star: # use * to match ( if stack_left[-1] > stack_star[-1]: # consider *( returnFalse stack_left.pop() stack_star.pop() returnlen(stack_left) == 0# stack_star can be non empty
defcheckValidString(self, s: str) -> bool: lo = hi = 0 for char in s: if char == '(': lo += 1 hi += 1 if char == '*': if lo > 0: # treat * as empty space lo -= 1 hi += 1 if char == ')': if lo > 0: # treat the previous * as empty space lo -= 1 hi -= 1 if hi < 0: # the num of right parenthesis > left ones returnFalse return lo == 0# the num of right parenthesis should equal to left ones
算法分析:
时间复杂度为O(n),空间复杂度O(n)
DP算法III解题思路:
基本情况为s[i], s[j] 分别在(*, )* 就合法 如果用单边DP,并不能确定区间内那些合法,所以只能用区间型DP dp[i][j] = s[i-1] == ‘*‘ and dp[i+1][j] 星号不匹配 = s[i-1] in ‘(*‘ and dp[i+1][k-1] and s[k-1] in (‘)*‘) and dp[k+1][j] 星号匹配
Given an array of points where points[i] = [x<sub>i</sub>, y<sub>i</sub>] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x<sub>1</sub> - x<sub>2</sub>)<sup>2</sup> + (y<sub>1</sub> - y<sub>2</sub>)<sup>2</sup>).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Example 1:
Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.