leetcode 132 Pattern

来源:互联网 发布:java socket 发送超时 编辑:程序博客网 时间:2024/05/16 13:57

456. 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.

Example 1:

Input: [1, 2, 3, 4]Output: FalseExplanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]Output: TrueExplanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]Output: TrueExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

import java.util.*;

public class Solution {
    public static boolean find132pattern(int[] nums) {  
        for(int k = nums.length - 1; k >=2; k --){  
            int i = 0, j = k -1;  
            while(i < j){  
                if(nums[i] < nums[k] && nums[k] < nums[j]){
                    return true;
                }  
                if(nums[i] >=nums[k]) i ++;  
                if(nums[j] <= nums[k]) j--;  
            }  
        }  
        return false;  
    }  
    
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
String line = reader.next();
String[] alist = line.substring(1, line.length()-1).split(",");
if(alist.length<3){
System.out.print(false);
}else if(alist.length<=15000){
int[] nums = new int[alist.length];
for(int i=0;i<nums.length;i++){
nums[i] = Integer.parseInt(alist[i]);
}
System.out.print(find132pattern(nums));
}
}


}
原创粉丝点击