leetcode_334 Increasing Triplet Subsequence
2016-06-01 23:01
316 查看
题目分析:
给定一个长度为n的乱序数组nums,求数组中是否存在i,j,k,使得num[i] < num[j] < num[k](0 <= i < j < k <= n-1)。
解题思路:
设x1为遍历到当前时的最小值,x2为遍历当前时最少有一个数比x2小的数。
初始时,将x1与x2均设置INT_MAX,然后遍历数组,不断更新x1和x2,其更原则为:
1)若nums[i] <= x1,则x1 = nums[i];
2)若x1 < num[i] <= x2,则x2 = nums[i]
3)nums[i] < x2,说明有解,返回true即可。
实质:不断缩小x1和x2,看是否存在第3个大于x2,存在,则为答案。
实现程序
C++版本
Java版本
参考文献
https://www.hrwhisper.me/leetcode-increasing-triplet-subsequence/
给定一个长度为n的乱序数组nums,求数组中是否存在i,j,k,使得num[i] < num[j] < num[k](0 <= i < j < k <= n-1)。
解题思路:
设x1为遍历到当前时的最小值,x2为遍历当前时最少有一个数比x2小的数。
初始时,将x1与x2均设置INT_MAX,然后遍历数组,不断更新x1和x2,其更原则为:
1)若nums[i] <= x1,则x1 = nums[i];
2)若x1 < num[i] <= x2,则x2 = nums[i]
3)nums[i] < x2,说明有解,返回true即可。
实质:不断缩小x1和x2,看是否存在第3个大于x2,存在,则为答案。
实现程序
C++版本
class Solution { public: bool increasingTriplet(vector<int> &nums) { int x1 = 0x7fffffff; int x2 = 0x7fffffff; for (int i = 0; i < nums.size(); i++) { if (nums[i] <= x1) x1 = nums[i]; else if (nums[i] <= x2) x2 = nums[i]; else return true; } return false; } };
Java版本
public boolean increasingTriplet(int[] nums){ int x1 = 0x7fffffff; int x2 = 0x7fffffff; for (int i = 0; i < nums.length; i++) { if (nums[i] <= x1){ // 记录遍历到当前时,出现的最小元素 x1 = nums[i]; } else if (nums[i] <= x2) { // 记录遍历到当前,出现的第二小的元素 x2 = nums[i]; } else { return true; } } return false; }
参考文献
https://www.hrwhisper.me/leetcode-increasing-triplet-subsequence/
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解