• 【数组】移动所有球到每个盒子所需的最小操作数


    1.题目描述

    给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

    混合字符串 由小写英文字母和数字组成。

    示例 1:

    输入:s = "dfa12321afd"
    输出:2
    解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。

    2.解题思路

    这里我们使用2种思路来解决上述问题:第一种使用max和secondMax来解决,secondMax代表第二大;第二种使用一个数组,然后从后往前遍历。

    2.1.方案1

    解决思路:

    • 准备max和secondMax;
    • 遍历数组
      • 遍历时case1,如果数组中的元素c比max大,则执行secondMax=max,max=c;
      • 遍历时case2,如果数组中的元素c比max小,则执行secondMax= Math.max(secondMax, c);
    • 最后返回:secondMax

    代码实现如下:

    1. class Solution {
    2. public int secondHighest(String s) {
    3. char[] arr = s.toCharArray();
    4. int max = -1;
    5. int secondMax = -1;
    6. for (char c : arr) {
    7. if (Character.isDigit(c)) {
    8. if (max < (c - '0')) {
    9. secondMax = max;
    10. max = c - '0';
    11. } else if(max > (c - '0')) {
    12. secondMax = Math.max(secondMax, c - '0');
    13. }
    14. }
    15. }
    16. return secondMax;
    17. }
    18. }

    2.2.方案2

    解决思路:

    • 准备数组int[] value = new int[10];
    • 遍历s,如果是数字,则执行value[c-'0']++;
    • 最后从9到0开始遍历,第二次出现的value[i]就是我们要的结果
    1. public int secondHighest(String s) {
    2. int[] value = new int[10];
    3. for (char c : s.toCharArray()) {
    4. if (c >= '0' && c <= '9') {
    5. value[c - '0']++;
    6. }
    7. }
    8. int count = 0;
    9. for (int i = 9; i >= 0; i--) {
    10. if (value[i] > 0) {
    11. count++;
    12. }
    13. if (count >= 2) {
    14. return i;
    15. }
    16. }
    17. return -1;
    18. }

    3.总结

    这里我们用了2种解法,第一种解法是标准解决方法,思路明确;第二种解法有些取巧的感觉,但是给我们提供了一套新的思路,并且执行效率也特别高。

  • 相关阅读:
    Harmony OS学习2
    898. 数字三角形
    2023年09月 Python(一级)真题解析#中国电子学会#全国青少年软件编程等级考试
    Python爬虫如何解决提交参数js加密
    Elasticsearch 认证模拟题 - 5
    iOS 屏幕录制实现
    mysql中的between边界问题
    LeetCode刷题---无重复字符的最长子串
    月子会所管理系统| 月子会所小程序| 数字化门店转型
    Illegal key size问题
  • 原文地址:https://blog.csdn.net/weiliuhong1/article/details/128158400