Python:检索两个下标,时间复杂度过高,超出时间限制
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
if nums[i] < nums[k] < nums[j]:
return True
return False
正确答案:解题思路(有方法二、三,实现更低的时间复杂度)
方法一:枚举3
Python
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
n = len(nums)
if n < 3:
return False
# 左侧最小值
left_min = nums[0]
# 右侧所有元素
right_all = SortedList(nums[2:])
for j in range(1, n - 1):
if left_min < nums[j]:
index = right_all.bisect_right(left_min)
if index < len(right_all) and right_all[index] < nums[j]:
return True
left_min = min(left_min, nums[j])
right_all.remove(nums[j + 1])
return False
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/132-pattern/solution/132mo-shi-by-leetcode-solution-ye89/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
C++
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int n = nums.size();
if (n < 3) {
return false;
}
// 左侧最小值
int left_min = nums[0];
// 右侧所有元素
multiset<int> right_all;
for (int k = 2; k < n; ++k) {
right_all.insert(nums[k]);
}
for (int j = 1; j < n - 1; ++j) {
if (left_min < nums[j]) {
auto it = right_all.upper_bound(left_min);
if (it != right_all.end() && *it < nums[j]) {
return true;
}
}
left_min = min(left_min, nums[j]);
right_all.erase(right_all.find(nums[j + 1]));
}
return false;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/132-pattern/solution/132mo-shi-by-leetcode-solution-ye89/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2021.03.24——力扣每日一题_456. 132模式