LeetCode Increasing Triplet Subsequence

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.

Solution:

模擬LIS的做法,不過只需要記錄最小的兩個就好。

因爲是遞增,所以在符合 

if (nums[i] > min_1 && nums[i] < min_2)

情況下,再給第二小的賦值

min_2 = nums[i];

Code:

public class Solution {
	public boolean increasingTriplet(int[] nums) {
		int len = nums.length;
		if (len <= 2)
			return false;
		int min_1 = Integer.MAX_VALUE;
		int min_2 = Integer.MAX_VALUE;

		for (int i = 0; i < len; i++) {
			if (nums[i] > min_2) {
				return true;
			}
			if (nums[i] < min_1) {
				min_1 = nums[i];
			} else if (nums[i] > min_1 && nums[i] < min_2) {
				min_2 = nums[i];
			}
		}

		return false;
	}
}


發佈了288 篇原創文章 · 獲贊 12 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章