题目:
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.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [5,4,3,2,1]
Output: false
题意:给定一个长度为n的乱序的数组arr,让你求是否有i,j,k三个数,使得 arr[i] < arr[j] < arr[k] ( 0 ≤ i < j < k ≤ n-1)
思路:
设 x1为到目前为止的最小值 , x2为到目前为止至少有一个(有可能有两个相等的数都比x2小)数比x2小的最小的数。
初始时设置x1 = x2 = INT_MAX ,然后遍历数组,不断的更新x1和x2 具体如下
- num < x1, 此时将x1设置为num
- 若 x1 < num < x2,则把x2设置为num
- x2 < num 说明有解,返回true即可
简单的说,上述的过程就是不断的缩小x1和x2,看看是否有第三个数比x2大。
如果出现第三个数 num > x2,则之前必定还有个数x1小于x2,就是说满足 x1 < x2 < num,就是说有答案啦。
代码:
public class IncreasingTripletSubsequence {
public static void main(String[] args) {
/**
* Example 1: Input: [1,2,3,4,5] Output: true
*/
int[] nums1 = { 1, 2, 3, 4, 5 };
System.out.println(increasingTriplet(nums1));
/**
* Example 2:
*
* Input: [5,4,3,2,1] Output: false
*/
int[] nums2 = { 5, 4, 3, 2, 1 };
System.out.println(increasingTriplet(nums2));
}
public static boolean increasingTriplet(int[] nums) {
int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < num1) {
num1 = nums[i];
} else if (nums[i] > num1 && nums[i] < num2) {
num2 = nums[i];
} else if (nums[i] > num2) {
return true;
}
}
return false;
}
}