✅ 682. 棒球比赛

描述

  1. 你现在是棒球比赛记录员。
  2. 给定一个字符串列表,每个字符串可以是以下四种类型之一:
  3. 1.整数(一轮的得分):直接表示您在本轮中获得的积分数。
  4. 2. "+"(一轮的得分):表示本轮获得的得分是前两轮有效 回合得分的总和。
  5. 3. "D"(一轮的得分):表示本轮获得的得分是前一轮有效 回合得分的两倍。# stack.top() *= 2
  6. 4. "C"(一个操作,这不是一个回合的分数):表示您获得的最后一个有效 回合的分数是无效的,应该被移除。# tt 对应队列的pop
  7. 每一轮的操作都是永久性的,可能会对前一轮和后一轮产生影响。
  8. 你需要返回你在所有回合中得分的总和。
  9. 示例 1:
  10. 输入: ["5","2","C","D","+"]
  11. 输出: 30
  12. 解释:
  13. 1轮:你可以得到5分。总和是:5
  14. 2轮:你可以得到2分。总和是:7
  15. 操作1:第2轮的数据无效。总和是:5
  16. 3轮:你可以得到10分(第2轮的数据已被删除)。总数是:15
  17. 4轮:你可以得到5 + 10 = 15分。总数是:30
  18. 示例 2:
  19. 输入: ["5","-2","4","C","D","9","+","+"]
  20. 输出: 27
  21. 解释:
  22. 1轮:你可以得到5分。总和是:5
  23. 2轮:你可以得到-2分。总数是:3
  24. 3轮:你可以得到4分。总和是:7
  25. 操作1:第3轮的数据无效。总数是:3
  26. 4轮:你可以得到-4分(第三轮的数据已被删除)。总和是:-1
  27. 5轮:你可以得到9分。总数是:8
  28. 6轮:你可以得到-4 + 9 = 5分。总数是13
  29. 7轮:你可以得到9 + 5 = 14分。总数是27
  30. 注意:
  31. 输入列表的大小将介于11000之间。
  32. 列表中的每个整数都将介于-3000030000之间

解答

多个 if 去判断 字符 就好了吧?

cpp

注意: stoi

注意: 你要好好记得 参数 : vector<string>& ops 里面的每一个都是string ,so use: “”

  1. Line 13: Char 31: error: no match for 'operator==' (operand types are '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >::value_type' {aka 'std::__cxx11::basic_string<char>'} and 'char')
  2. } else if (ops[i] == 'D') { // tt change it to "D" will be fine
  1. class Solution {
  2. public:
  3. int calPoints(vector<string>& ops) {
  4. int ret = 0;
  5. stack<int> s;
  6. for (int i = 0; i < ops.size(); i++) {
  7. if(ops[i] == "+") {
  8. int a = s.top();
  9. s.pop();
  10. int b = s.top();
  11. s.push(a);
  12. s.push(a + b);
  13. } else if (ops[i] == "D") {
  14. int a = s.top();
  15. s.push(2 * a);
  16. } else if (ops[i] == "C") {
  17. s.pop();
  18. } else {
  19. s.push(stoi(ops[i]));// stoi will cause one char in ops convert to an integer.
  20. }
  21. }
  22. while(!s.empty()) {
  23. ret += s.top();
  24. s.pop();
  25. }
  26. return ret;
  27. }
  28. };
  29. /*执行用时 :
  30. 8 ms
  31. , 在所有 C++ 提交中击败了
  32. 71.81%
  33. 的用户
  34. 内存消耗 :
  35. 9.8 MB
  36. , 在所有 C++ 提交中击败了
  37. 5.10%
  38. 的用户*/

py

  1. class Solution:
  2. def calPoints(self, ops: List[str]) -> int:
  3. scores = []
  4. for i in ops:
  5. if i == '+':
  6. scores += [sum(scores[-2:])]# this will add last two in list
  7. # list0 can be append by list1 + list2,so u got: [1,2,3] = [1] + [2,3]
  8. elif i == 'D':
  9. scores += [scores[-1] * 2]
  10. elif i == 'C':
  11. scores.pop()
  12. else:
  13. scores += [int(i)]
  14. return sum(scores)
  15. '''
  16. 执行用时 :
  17. 40 ms
  18. , 在所有 Python3 提交中击败了
  19. 84.49%
  20. 的用户
  21. 内存消耗 :
  22. 13.1 MB
  23. , 在所有 Python3 提交中击败了
  24. 44.70%
  25. 的用户
  26. '''

✅ 999. 车的可用捕获量

描述

  1. 在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有 空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 R”,“.”,“B p 给出。大写字符表示白棋,小写字符表示黑棋。
  2. 车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格来捕获该方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。
  3. 返回车能够在一次移动中捕获到的卒的数量。
  4.  

解答

c

  1. int numRookCaptures(char** board, int boardSize, int* boardColSize){
  2. int x,y,res=0;
  3. // 找 车
  4. for(int i=0;i<8;i++){
  5. for(int j=0;j<8;j++){
  6. if(board[i][j]=='R'){
  7. x=i;y=j;
  8. break;
  9. }
  10. }
  11. }
  12. // 四个方向开车
  13. for(int i=x+1;i<8;i++){
  14. if(board[i][y]=='B')break;
  15. if(board[i][y]=='p'){
  16. res++;
  17. break;
  18. }
  19. }
  20. for(int i=x-1;i>=0;i--){
  21. if(board[i][y]=='B')break;
  22. if(board[i][y]=='p'){
  23. res++;
  24. break;
  25. }
  26. }
  27. for(int i=y+1;i<8;i++){
  28. if(board[x][i]=='B')break;
  29. if(board[x][i]=='p'){
  30. res++;
  31. break;
  32. }
  33. }
  34. for(int i=y-1;i>=0;i--){
  35. if(board[x][i]=='B')break;
  36. if(board[x][i]=='p'){
  37. res++;
  38. break;
  39. }
  40. }
  41. return res;
  42. }

other java todo

  1. class Solution {
  2. public int numRookCaptures(char[][] board) {
  3. for(int i=0;i<board.length;i++){
  4. for(int j=0;j<board[i].length;j++){
  5. //找到R的位置
  6. if(board[i][j]=='R'){
  7. //以R 为原点建立坐标系
  8. //依次向上找,向下找,向右找,向左找
  9. return cap(board,i,j,0,1)+cap(board,i,j,0,-1)+cap(board,i,j,1,0)+cap(board,i,j,-1,0);
  10. }
  11. }
  12. }
  13. return 0;
  14. }
  15. public int cap(char[][] a,int x,int y,int dx,int dy){
  16. /*参数说明
  17. *a为原数组矩阵
  18. *x,y为R的坐标
  19. *dx,dy为增长步长
  20. */
  21. while(x>=0 && x<a.length && y>=0 && y<a[x].length && a[x][y]!='B'){
  22. if(a[x][y]=='p'){
  23. return 1;
  24. }
  25. x+=dx;
  26. y+=dy;
  27. }
  28. return 0;
  29. }

py

  1. class Solution:
  2. def numRookCaptures(self, board: List[List[str]]) -> int:
  3. #首先找到车所在的行和列
  4. output = 0
  5. col = None
  6. row = None
  7. for i in range(len(board)):
  8. if 'R' in board[i]:
  9. row = i
  10. break
  11. col = board[row].index('R')# 值得注意 list.index(some_ele)
  12. # 找到了 车 的 row and col
  13. # 接下来 从 行,从列找 车能捕获 的 卒
  14. # 行:
  15. s = ''.join(board[row])
  16. # now s is??? guess == board[row]
  17. s = s.replace('.', '')# replace all 空方块('.') with really empty ''
  18. # count
  19. if 'pR' in s:
  20. output += 1
  21. if 'Rp' in s:
  22. output += 1
  23. # col:
  24. s = ''.join(traversedRow[col] for traversedRow in board)
  25. s = s.replace('.', '')# replace all 空方块('.') with really empty ''
  26. # count
  27. if 'pR' in s:
  28. output += 1
  29. if 'Rp' in s:
  30. output += 1
  31. return output
  32. '''
  33. 执行用时 :
  34. 32 ms
  35. , 在所有 Python3 提交中击败了
  36. 81.42%
  37. 的用户
  38. 内存消耗 :
  39. 13 MB
  40. , 在所有 Python3 提交中击败了
  41. 51.13%
  42. 的用户
  43. '''

✅ 118. 杨辉三角

https://leetcode-cn.com/problems/pascals-triangle/

描述

pascal triangle

  1. 在杨辉三角中,每个数是它左上方和右上方的数的和。
  2. 示例:
  3. 输入: 5
  4. 输出:
  5. [
  6. [1],
  7. [1,1],
  8. [1,2,1],
  9. [1,3,3,1],
  10. [1,4,6,4,1]
  11. ]

解答

cpp


  1. //c:
  2. /**
  3. * Return an array of arrays of size *returnSize.
  4. * The sizes of the arrays are returned as *returnColumnSizes array.
  5. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
  6. */
  7. int** generate(int numRows, int* returnSize, int** returnColumnSizes){
  8. *returnSize = numRows;
  9. *returnColumnSizes = (int *)malloc(sizeof(int) * numRows);//存贮每行有几个数字; 比如,第一行 1 个,第二行 2个。后面有 赋值
  10. int **ret = (int **) malloc(sizeof(int *) * numRows);//我被返回,我每行存int ptr
  11. for(int i = 0; i < numRows; i++) {
  12. (*returnColumnSizes)[i] = i + 1;
  13. ret[i] = (int *) malloc (sizeof(int) * (i + 1));//每行分配i+1 个空间大小
  14. ret[i][0] = 1;
  15. ret[i][i] = 1;
  16. //开头 ,结尾 已经 赋值为1 ,ok
  17. // 然后,我依次加到下面的行
  18. // 注意:第一行不会执行 这个for
  19. for(int j = 1; j < i; j++) {
  20. ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1];//add zheng top, and left top
  21. }
  22. }
  23. return ret;
  24. }
  25. /*执行用时 :
  26. 4 ms
  27. , 在所有 C 提交中击败了
  28. 76.92%
  29. 的用户
  30. 内存消耗 :
  31. 7.2 MB
  32. , 在所有 C 提交中击败了
  33. 75.09%
  34. 的用户*/
  35. //c++
  36. class Solution {
  37. public:
  38. vector<vector<int>> generate(int numRows) {
  39. vector<vector<int>> vec;
  40. for(int i= 0;i < numRows;i++){
  41. vec.push_back(vector<int> (i+1,1));//初始化为 i + 1 那么大,每个元素为1
  42. if(i > 1){
  43. for(int j = 1; j < i; j++){
  44. vec[i][j] = vec[i-1][j-1] + vec[i-1][j];
  45. }
  46. }
  47. }
  48. return vec;
  49. }
  50. };
  51. /*执行用时 :
  52. 4 ms
  53. , 在所有 C 提交中击败了
  54. 76.92%
  55. 的用户
  56. 内存消耗 :
  57. 7.2 MB
  58. , 在所有 C 提交中击败了
  59. 75.09%
  60. 的用户*/

py

  1. class Solution:
  2. def generate(self, numRows: int) -> List[List[int]]:
  3. ret = []
  4. for i in range(numRows):
  5. now = [1] * (i+1)
  6. if i >= 2:
  7. for n in range (1, i):
  8. now[n] = pre[n - 1] + pre[n]
  9. ret += [now] # add now(the list [3,4,5]) as one single list ele
  10. pre = now
  11. return ret
  12. '''
  13. 执行用时 :
  14. 28 ms
  15. , 在所有 Python3 提交中击败了
  16. 90.60%
  17. 的用户
  18. 内存消耗 :
  19. 12.9 MB
  20. , 在所有 Python3 提交中击败了
  21. 50.43%
  22. 的用户
  23. '''

✅ 258. 各位相加

https://leetcode-cn.com/problems/add-digits

描述

  1. 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
  2. 示例:
  3. 输入: 38
  4. 输出: 2
  5. 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2 由于 2 是一位数,所以返回 2
  6. 进阶:
  7. 你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

解答

X = 100a + 10b + c = 99a + 9b + (a+b+c);所以对9取余即可。

接受降维打击吧 各位: return 1 + (num - 1) % 9;

cpp

  1. //递归
  2. class Solution {
  3. public:
  4. int addDigits(int num) {
  5. if(num < 10) {
  6. return num;
  7. }
  8. int newInt = 0;
  9. while(num != 0) {
  10. newInt += num % 10;
  11. num /= 10;
  12. }
  13. return addDigits(newInt);
  14. }
  15. };
  16. /*执行用时 :
  17. 8 ms
  18. , 在所有 C++ 提交中击败了
  19. 30.57%
  20. 的用户
  21. 内存消耗 :
  22. 8.2 MB
  23. , 在所有 C++ 提交中击败了
  24. 39.39%
  25. 的用户*/

py

找到规律:理解todo

除了传统的单纯循环,还可以找规律。假如一个三位数'abc',其值大小为s1 = 100 * a + 10 * b + 1 * c,经过一次各位相加后,变为s2 = a + b + c,减小的差值为(s1 -s2) = 99 * a + 9 * b 差值可以被9整除,每一个循环都这样,缩小了9的倍数。当num小于9,即只有一位时,直接返回num,大于9时,如果能被9整除,则返回9(因为不可能返回0也不可能返回两位数及以上的值),如果不能被整除,就返回被9除的余数。

  1. class Solution:
  2. def addDigits(self, num: int) -> int:
  3. if num > 9:
  4. num = num % 9
  5. if num == 0:
  6. return 9
  7. return num

leetcode 0217的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

随机推荐

  1. OSI七层协议详解

    一.简介 开放系统互连参考模型 (Open System Interconnect 简称OSI)是国际标准化组织(ISO)和国际电报电话咨询委员会(CCITT)联合制定的开放系统互连参考模型,为开放式 ...

  2. DFA 简易正则表达式匹配

    一个只能匹配非常简单的(字母 . + *)共 4 种状态的正则表达式语法的自动机(注意,仅限 DFA,没考虑 NFA): 好久之前写的了,记得有个 bug 一直没解决... #include < ...

  3. Unity相机跟随

    固定相机跟随 这种相机有一个参考对象,它会保持与该参考对象固定的位置,跟随改参考对象发生移动 using UnityEngine; using System.Collections; public c ...

  4. Java学习笔记(九)面向对象---模板方法设计模式

    理解 在定义功能时功能的一部分是确定的,但是有一部分是不确定的,而确定的部分在使用不确定的部分,那么就将不确定的部分暴露出去,由该类的子类完成. 举例 需求 获取一段程序的运行时间 代码 abstra ...

  5. 【代码审计】seacms 前台Getshell分析

    一.漏洞分析 漏洞触发点search.php 211-213行 跟进parseIf 函数 ./include/main.class.php 这里要注意 3118行的位置,可以看到未做任何处理的eval ...

  6. Go_栈

    1. 栈的介绍 2. 栈的应用 3. 栈入门 package main import ( "fmt" "errors" ) //使用数组来模拟一个栈的使用 ty ...

  7. flask 2 进阶

    # 创建项目 jinja2 语法基础 # pycharm 里面 创建 new project -->pure python 之后选择路径 选择解释器 以及虚拟环境问题 from flask im ...

  8. Intersection over Union(IoU) algorithms

    IoU算法可用与评估两个多维度数据的相似度,举一个实际应用,做CV,目标检测,我们需要评估模型的识别准确率,不同于二元类问题,普通的评估算法不合适,于是用到了这个算法,这个算法简单易懂,评估效果也不错 ...

  9. Anaconda"无法定位程序输入点 OPENSSL_sk_new_reserve 于动态链接库Anaconda3\Library\bin\libssl-1_1-x64.dll上"的解决办法

    Anaconda"无法定位程序输入点 OPENSSL_sk_new_reserve 于动态链接库Anaconda3\Library\bin\libssl-1_1-x64.dll上" ...

  10. itest(爱测试) 4.3.0 发布,开源BUG 跟踪管理 & 敏捷测试管理软件

    itest 简介:查看简介 test 开源敏捷测试管理,testOps 践行者.可按测试包分配测试用例执行,也可建测试迭代(含任务,测试包,BUG)来组织测试工作,也有测试环境管理,还有很常用的测试度 ...