关闭

Leetcode-334. Increasing Triplet Subsequence

标签: Leetcode334
87人阅读 评论(0) 收藏 举报
分类:

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.

Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.
译:
给定一个未排序的数组; 返回其中是否存在3个数 这三个数 arr[i] < arr[j] < arr[k] 并且 0 ≤ i < j < k ≤ n-1;
你的算法空间复杂度为O(1);时间复杂度为O(n) ;

public static boolean increasingTriplet(int[] nums) {

        for (int i = 0; i < nums.length - 2; i++) {

            for (int j = i + 1; j < nums.length - 1; j++) {

                if (nums[j] > nums[i]) {

                    for (int k = j + 1; k < nums.length; k++) {

                        if (nums[k] > nums[j]) {

                            System.out.println("i=" + i + " a[" + i + "]"

                                    + nums[i]);

                            System.out.println("j=" + j + " a[" + j + "]"

                                    + nums[j]);

                            System.out.println("k=" + k + " a[" + k + "]"

                                    + nums[k]);

                            return true;

                        }

                    }

                }

            }

        }

        return false;

    }

} 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15533次
    • 积分:584
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:4篇
    • 译文:33篇
    • 评论:3条
    最新评论