TypechoJoeTheme

IT技术分享

统计

[LeetCode 334] Increasing Triplet Subsequence [Java]

2017-11-06
/
0 评论
/
740 阅读
/
正在检测是否收录...
11/06

1. Description

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.

2. Example

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

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

3. Code


public class LeetCode0334 { public boolean increasingTriplet(int[] nums) { if(nums == null || nums.length < 3){ return false; } int x = Integer.MAX_VALUE; int y = Integer.MAX_VALUE; for(int i =0; i< nums.length;i++){ if(x >= nums[i]){ x = nums[i]; }else if(y >= nums[i]){ y = nums[i]; }else{ return true; } } return false; } public static void main(String[] args) { LeetCode0334 leetcode = new LeetCode0334(); int[] nums = new int[]{5, 4, 3, 2, 1}; System.out.println(leetcode.increasingTriplet(nums)); } }
Digital
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1244/(转载时请注明本文出处及文章链接)