当前位置: 首页 > article >正文

Java | Leetcode Java题解之第456题132模式

题目:

题解:

class Solution {
    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        List<Integer> candidateI = new ArrayList<Integer>();
        candidateI.add(nums[0]);
        List<Integer> candidateJ = new ArrayList<Integer>();
        candidateJ.add(nums[0]);

        for (int k = 1; k < n; ++k) {
            int idxI = binarySearchFirst(candidateI, nums[k]);
            int idxJ = binarySearchLast(candidateJ, nums[k]);
            if (idxI >= 0 && idxJ >= 0) {
                if (idxI <= idxJ) {
                    return true;
                }
            }
            
            if (nums[k] < candidateI.get(candidateI.size() - 1)) {
                candidateI.add(nums[k]);
                candidateJ.add(nums[k]);
            } else if (nums[k] > candidateJ.get(candidateJ.size() - 1)) {
                int lastI = candidateI.get(candidateI.size() - 1);
                while (!candidateJ.isEmpty() && nums[k] > candidateJ.get(candidateJ.size() - 1)) {
                    candidateI.remove(candidateI.size() - 1);
                    candidateJ.remove(candidateJ.size() - 1);
                }
                candidateI.add(lastI);
                candidateJ.add(nums[k]);
            }
        }

        return false;
    }

    public int binarySearchFirst(List<Integer> candidate, int target) {
        int low = 0, high = candidate.size() - 1;
        if (candidate.get(high) >= target) {
            return -1;
        }
        while (low < high) {
            int mid = (high - low) / 2 + low;
            int num = candidate.get(mid);
            if (num >= target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }

    public int binarySearchLast(List<Integer> candidate, int target) {
        int low = 0, high = candidate.size() - 1;
        if (candidate.get(low) <= target) {
            return -1;
        }
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            int num = candidate.get(mid);
            if (num <= target) {
                high = mid - 1;
            } else {
                low = mid;
            }
        }
        return low;
    }
}

http://www.kler.cn/news/340318.html

相关文章:

  • 程序bug修复的艺术与科学
  • 【开源项目推荐】开源ERP系统:探索企业管理的无限可能
  • C++语言学习(1): std::endl 在做什么?
  • [论文阅读] DVQA: Understanding Data Visualizations via Question Answering
  • Java数据类型常量
  • 【光追模组】雷神之锤4光追mod,调色并修改光影,并且支持光追效果,游戏画质大提升
  • nginx从入门到精通
  • 系统架构师备考记忆不太清楚的点-信息系统-需求分析
  • C++学习笔记(51)
  • 【算法】- 查询 -平衡二叉树
  • microsoft edge浏览器卡死问题
  • python基础语法全解(两万字讲解,建议收藏)
  • cudnn8编译caffe过程(保姆级图文全过程,涵盖各种报错及解决办法)
  • Python使用技巧:注释和输出
  • 简述何为多态
  • 【MAUI】【Bug】UserDialogs.Instance.ShowLoading在ViewModel失效?
  • 揭秘开发者的效率倍增器:编程工具的选择与应用
  • 聚观早报 | 苹果重磅更新;OpenAI推出ChatGPT Canvas
  • 网站优化门槛低了还是高了?
  • 二层网络和三层网络的理解与区别(包含通俗理解和归纳总结)