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

问题:

难度:medium

说明:

给出一个数组 nums,和一个长度 K,要求返回一个长度 K 的数组,该数组属于原数组 nums 的子序列,然后要求返回数组是最具有竞争力,其实就是子序列的数字相对原数组顺序,前端序的都是最小的。

题目连接:https://leetcode.com/problems/find-the-most-competitive-subsequence/

输入范围:

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

输入案例:

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]

我的代码:

因为输入长度不可能全排列的,所以用单调栈,然后需要对比下单调栈长度和对比的起始位置就好。

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/112980730