334. Increasing Triplet Subsequence (用 C 語言解題)

Medium
Topics
Companies

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

 

Example 1:

Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.

Example 2:

Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.

Example 3:

Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

 

Constraints:

  • 1 <= nums.length <= 5 * 105
  • -231 <= nums[i] <= 231 - 1

 

Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?


google 翻譯:

給定一個整數數組 nums,如果存在三個索引 (i, j, k),使得 i < j < k
nums[i] < nums[j] < nums[k],則傳回 true。 如果不存在這樣的索引,則傳回 false


想法一:


簡單的想法,用三個 for 一層一層包起來,就可以得到答案了

寫法一:

bool increasingTriplet(int* nums, int numsSize) {
int i, j, k;
for(i=0; i<numsSize-2; i++) { // 最小的值只到 numsSize - 2
for(j=i; j<numsSize-1; j++) { // 中間的值 只到 numsSize -1
for(k=j; k<numsSize; k++) { // 最大的值要跑完整個迴圈
if(nums[i] < nums[j] && nums[j] < nums[k])
return 1;
}
}
}
return 0;
}

結果一:
跑太久啦,來想辦法加執行速度囉...


想法二:


僅跑一次迴圈,在中途記錄最小值與中間值,一併判斷中間值與最大值

寫法二:

bool increasingTriplet(int* nums, int numsSize) {
int i, left=INT_MAX, middle =INT_MAX;
for(i=0; i<numsSize; i++) {
if(nums[i] > middle) {
// 中間值 < 目前值 就可回傳 true
return 1;
} else if(nums[i] < left) {
// 有更小值,存入 left
left = nums[i];
} else if(left < nums[i] && middle > nums[i]) {
// 最小值 < 目前值 and 目前值 比 中間值更小,存入較小值 middle
// 到此為止 nums[i] < nums[j] 已成立
// 所以之後只要 nums[j] < nums[k] 成立即可回傳 true
middle = nums[i];
}
}
return 0;
}

結果二:
雖然結果不盡理想,但變動後的進展也不大,就這樣吧...



沒有留言:

張貼留言