LeetCode OJ 456 132 Pattern [Medium]

题目描述:

Given a sequence ofn integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such thati < j < k and ai < ak < aj. Design an algorithm that takes a listof 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: False

Explanation: Thereis no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: Thereis a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: Thereare three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

题目理解 :

给定一个有n个数的整数序列,判断是否为132序列

132序列定义:这个序列中存在 小的在大的前面,大的后面有一个数的大小介于中间的这样一个序列。

我的分析:

1.   对一个序列,找一个smaller,找一个bigger,smaller在bigger之前,在bigger之后有一个介于它们中间的数

2. 如图分析:在序列smaller,bigger之后存在一个大小介于它们之间的数字

               

3.  无论当升序(当前值比前面的大)还是降序(当前值比前面的小),都首先考虑是否符合132 patter,若是,则返回true。

4.  若不符合132 patter:

(1)  若是升序,则 更改/不改 当前上升线的最大值bigger

(2)  若是降序,则开始新的上升线,填写新的smaller

5.  用两个数组smaller,bigger来存储每条上升线的最小值和最大值,索引相同表示是一条上升线,如smaller[2]和bigger[2]表示一条上升线的最小值和最大值

我的解答:

static public boolean find132pattern(int[] nums) {
    if(nums.length == 0)
        return false;
    int[] smaller = new int[15000];
    int[] bigger = new int[15000];
    for (int i = 0; i < smaller.length; i++) {
        smaller[i] = Integer.MAX_VALUE;
        bigger[i] = Integer.MIN_VALUE;
    }
    smaller[0] = nums[0];


    for (int i = 0, j = 0; i < nums.length - 1; i++) {
        for (int n = 0; n <= j; n++) {
            if (nums[i + 1] > smaller[n] && nums[i + 1] < bigger[n]) {
                return true;
            }
        }
        if (nums[i] < nums[i + 1]) {
            if (nums[i + 1] > bigger[j]) {
                bigger[j] = nums[i + 1];
            }
        }
        else if (nums[i] > nums[i + 1]) {
           j += 1;
           smaller[j] = nums[i+1];
        }
    }
    return false;
}


其他解答:

I use the variables begand end to keep track of minimum subarray A[beg...end] which must be sorted forthe entire array A to be sorted. If end < beg< 0 at the end of the for loop, then thearray is already fully sorted.

public int findUnsortedSubarray(int[] A) {
    int n = A.length, beg = -1, end = -2, min = A[n-1], max = A[0];
    for (int i=1;i<n;i++) {
        max = Math.max(max, A[i]);
        min = Math.min(min, A[n-1-i]);
        if (A[i] < max) end = i;
        if (A[n-1-i] > min) beg = n-1-i;
    }
    return end - beg + 1;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值