0
点赞
收藏
分享

微信扫一扫

Java&C++题解与拓展——leetcode682.棒球比赛【C++ auto学习与使用】

炽凤亮尧 2022-03-26 阅读 20
每日一题做题记录,参考官方和三叶的题解

目录

题目要求

在这里插入图片描述

思路

就、直接模拟、上就完了。
简单到甚至写不出来注释。
Java和Python3方法一样,维护数组最后相加;C++方法同步计算结果,维护一个vector定义的栈。

Java

class Solution {
    static int[] poi = new int[1001];
    public int calPoints(String[] ops) {
        int len = ops.length, idx = 0;
        for(int i = 0; i < len; i++, idx++) {
            if(ops[i].equals("+"))
                poi[idx] = poi[idx - 1] + poi[idx - 2];
            else if(ops[i].equals("D"))
                poi[idx] = poi[idx - 1] * 2;
            else if(ops[i].equals("C"))
                idx -= 2;
            else
                poi[idx] = Integer.parseInt(ops[i]);
        }
        int res = 0;
        for(int i = 0; i < idx; i++)
            res += poi[i];
        return res;
    }
}
  • 时间复杂度: O ( n ) O(n) O(n) n n n为数组ops的大小,遍历一遍ops
  • 空间复杂度: O ( n ) O(n) O(n)

C++

class Solution {
public:
    int calPoints(vector<string>& ops) {
        int res = 0;
        vector<int> poi;
        for(auto &op : ops) {
            int len = poi.size();
            switch(op[0]) {
                case '+':
                    res += poi[len - 1] + poi[len - 2];
                    poi.push_back(poi[len - 1] + poi[len - 2]);
                    break;
                case 'D':
                    res += poi[len - 1] * 2;
                    poi.push_back(2 * poi[len -  1]);
                    break;
                case 'C':
                    res -= poi[len - 1];
                    poi.pop_back();
                    break;
                default:
                    res += stoi(op);
                    poi.push_back(stoi(op));
                    break;
            }
        }
        return res;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)

auto

  • 学习参考链接
  • 简介
    • C++ 11中引入的类型推导关键字,用于方便获取复杂的类型。【类似C#中的var】;
    • 不是实际的类型声明,只是一个类型声明的占位符,拿来声明变量编译不过。需直接初始化,以让编译器推断其实际类型,在编译时将占位符auto换为准确类型。
  • 适用场景就是类似上面,类型名超级长的情况,用来偷懒。
    • 不使用的话就要写for(vector<string>& op : ops)

Python3

class Solution:
    def calPoints(self, ops: List[str]) -> int:
        res = 0
        poi = []
        for op in ops:
            if op == '+':
                p = poi[-1] + poi[-2]
            elif op == 'D':
                p = poi[-1] * 2
            elif op == 'C':
                res -= poi.pop()
                continue
            else:
                p = int(op)
            res += p
            poi.append(p)
        return res
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)

总结

简单到想回去睡一觉的模拟题,早上起来是久违的阳光明媚,美好的周末开始了。


欢迎指正与讨论!
举报

相关推荐

0 条评论