于是我要开始做俗之又俗的leetCode刷题记录了。
一方面是贡献给大家题目的解,另一方面是督促自己刷题,希望每天都有至少一篇刷题的记录。
题目基本上都是leetCode的medium或者hard题,easy题目看看就行。
今天先来一发水水的题目~
leetcode456. 132 Pattern
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
大致意思是给一个整数数列,问其中有没有这样的子序列:ai, aj, ak (i < j < k )并且 ai < ak < aj,有的话返回true,没有的话返回false。
一开始考虑的是,完全遍历每一个三元组,查看是否符合要求,但是这种方法显然时间复杂度为O(N3),而考虑到n是1万5的这个数量级,很容易就知道,时间复杂度太高了。
于是考虑到,并不需要遍历每一个三元组,只需要找到头尾两个值,看中间是否存在一个值大于头尾,并且尾值大于头值,这个过程直接通过遍历取max就可以得到。
于是时间复杂度被降低到了O(n2)。
代码如下:
public class Solution {
public boolean find132pattern(int[] nums) {
if(nums.length<3)
return false;
for(int i = 0;i<nums.length;i++){
int max = Integer.MIN_VALUE;
for(int j = i+1;j<nums.length;j++){
if(max<nums[j]){
max = nums[j];
}
if(max>nums[j]&&max>nums[i]&&nums[i]<nums[j]){
return true;
}
}
}
return false;
}
}