2293.极大极小游戏
链接:2293.极大极小游戏
难度:Easy
标签:数组、模拟
简介:执行算法后,返回 nums 中剩下的那个数字。
题解 1 - cpp
- 编辑时间:2023-01-15
- 执行用时:4ms
- 内存消耗:9.8MB
- 编程语言:cpp
- 解法介绍:递归。
class Solution {
public:
    int minMaxGame(vector<int>& nums) {
        int n = nums.size();
        if (n == 1) return nums[0];
        vector<int> next(n / 2, 0);
        for (int i = 0, f = 1; i < n; i += 2, f ^= 1) {
            if (f) next[i / 2] = min(nums[i], nums[i + 1]);
            else next[i / 2] = max(nums[i], nums[i + 1]);
        }
        return minMaxGame(next);
    }
};
题解 2 - rust
- 编辑时间:2023-01-15
- 执行用时:4ms
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn min_max_game(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        if n == 1 {
            nums[0]
        } else {
            let mut next = vec![0; n / 2];
            let mut i = 0;
            let mut f = true;
            while i < n {
                next[i / 2] = if f {
                    nums[i].min(nums[i + 1])
                } else {
                    nums[i].max(nums[i + 1])
                };
                i += 2;
                f = !f;
            }
            Solution::min_max_game(next)
        }
    }
}