zoukankan      html  css  js  c++  java
  • Increasing Triplet Subsequence

    Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

    Formally the function should:

    Return true if there exists i, j, k 
    such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

    Your algorithm should run in O(n) time complexity and O(1) space complexity.

    Examples:
    Given [1, 2, 3, 4, 5],
    return true.

    Given [5, 4, 3, 2, 1],
    return false.

    题目大意:

    给一个没有排序的整数数组,如果数组存在三个数依次递增,返回true,否则返回false。其中三个数位置关系满足:array[i] < array[j] < array[k], i < j < k

    也就是说,三个数以及数组中的位置只要依次递增即可。

    思路一:

    遍历数组中的所有元素,三个数组和的所有情况,枚举所有可能进行判断

    简单粗暴,时间复杂度较高O(N ^ 3),空间复杂度O(1)

     1 public class Solution {
     2     public boolean increasingTriplet(int[] nums) {
     3         if(nums == null || nums.length < 3)
     4             return false;
     5         boolean found = false;
     6         for(int i = 0; i < nums.length - 2 && !found; i++){
     7             for(int j = i + 1; j < nums.length - 1 && !found; j++){
     8                 for(int k = j + 1; k < nums.length; k++){
     9                     if(nums[i] < nums[j] && nums[j] < nums[k]){
    10                         found = true;
    11                         break;
    12                     }//if
    13                 }//for k
    14             }//for j
    15         }//for i
    16         
    17         return found;
    18     }//increasingTriplet
    19 }

    java写的,运行时间166ms

    思路二:

    刷了好几道这种题,题目也有提示,存在O(N)的解决方案。根据经验,个人觉得没必要例举所有的可能性,我们要直接奔着结果去,看结果需要什么。没必要把不必要的的找出来,增加复杂度。这道题我其实有思路,但没想通,看了讨论区一个用C++写的。我跟他的想法方向一致,不过还是没有想出来。

    照着他的思路写了一下java版的

     1 public class Solution {
     2     public boolean increasingTriplet(int[] nums) {
     3         if(nums == null || nums.length < 3)
     4             return false;
     5         int min = Integer.MAX_VALUE;
     6         int mid = Integer.MAX_VALUE;
     7         for(int num : nums){
     8             if(num < min)
     9                 min = num;
    10             else if(num  > min){
    11                 if(num > mid)
    12                     return true;
    13                 mid = num;
    14             }//else
    15         }//for
    16         
    17         return false;
    18     }//increasingTriplet
    19 }

    运行时间1ms

    讨论区c++解决方案链接:https://leetcode.com/discuss/95137/my-c-o-n-solution

  • 相关阅读:
    jQuery中时间戳和日期的相互转换
    jquery append 方法应用
    MySQL中实现连续日期内数据统计,缺省天数0补全
    jQuery通过ajax请求php遍历json数组到table中的代码
    sql相同表不同查询条件合并显示
    paginate()出来的数据怎样循环插入数据?
    使用paginate分页后数据处理
    ThinkPhp3.2.3 使用phpExcel导入数据
    判断时间戳是星期几
    英文加数字升序/降序
  • 原文地址:https://www.cnblogs.com/luckygxf/p/5597671.html
Copyright © 2011-2022 走看看