[Leetcode学习-c++&java]Find the Most Competitive Subsequence

problem:

Difficulty: medium

Description:

Given an array nums and a length K, it is required to return an array of length K, which belongs to the subsequence of the original array nums , and then the return array is required to be the most competitive. In fact, it is the order of the numbers of the subsequence relative to the original array. The front-end sequence is the smallest.

Subject link: https://leetcode.com/problems/find-the-most-competitive-subsequence/

Input range:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 1 <= k <= nums.length

Enter the case:

Example 1:
Input: nums = [3,5,2,6], k = 2
Output: [2,6]
Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.

Example 2:
Input: nums = [2,4,3,3,5,4,9,6], k = 4
Output: [2,3,3,4]

My code:

Because the input length can not be arranged in full, so use a monotonic stack, and then need to compare the length of the monotonic stack and the starting position of the comparison .

Java:

class Solution {
    public int[] mostCompetitive(int[] nums, int k) {
        int len = nums.length, index = 0;
        int[] res = new int[k];
        Arrays.fill(res, Integer.MAX_VALUE);
        for(int i = 0; i < len; i ++) {
            boolean flag = true; // 判断是否将数据插入标记
            int top = index, begin = len - i >= k ? 0 : k - len + i; // 计算单调栈比较开端索引
            while(top - 1 >= begin && res[top - 1] > nums[i]) { // top是比最后一个元素多1,并且要先 -1 判断再进行 -1
                res[-- top] = nums[i];
                flag = false;
            }
            if(!flag) index = top + 1; // 重新给index赋值
            else if(index < k) res[index ++] = nums[i];
        }
        return res;
    }
}

C++:

class Solution {
public:
    vector<int> mostCompetitive(vector<int>& nums, int k) {
        vector<int> res(k, INT_MAX); // 填满最大值
        int index = 0, len = nums.size();
        for(int i = 0; i < len; i ++) {
            bool flag = true;
            int top = index, begin = len - i >= k ? 0 : k - len + i;
			while (top - 1 >= begin && nums[i] < res[top - 1]) {
                res[-- top] = nums[i];
                flag = false;
            }
            if(!flag) index = top + 1;
            else if(index < k) res[index ++] = nums[i];
        }
        return res;
    }
};

 

 

 

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/112980730