【每日一题Day46】LC1796字符串中第二大的数字 | 模拟

字符串中第二大的数字【LC1796】

Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.

快快学完今天的,然后去做菜

  • 思路:遍历字符串,使用变量记录字符串中第一大 f i r s t H firstH firstH和第二大的整数值 s e c o n d H secondH secondH,当遇到一个整数 n u m num num时进行判断

    • n u m > f i r s t H num>firstH num>firstH时, n u m num num即为当前数组第一大, f i r s t H firstH firstH为第二大
    • n u m < f i r s t H numnum<firstH并且 n u m > s e c o n d H num>secondH num>secondH时, n u m num num即为当前数组第二大
    • 注意:当 n u m = = f i r s t H num==firstH num==firstH时,不做任何处理
  • 实现

    class Solution {
        public int secondHighest(String s) {
            int firstH = -1;
            int secondH = -1;
            for (char c : s.toCharArray()){
                if (c >= '0' && c <= '9'){
                    int num = c -'0';
                    if (num > firstH) {
                        secondH = firstH;
                        firstH = num;
                    }else if (num < firstH && num > secondH) {
                        secondH = num;
                    }
                }
            }
            return secondH;
        }
    }
    
    • 复杂度

      • 时间复杂度: O ( n ) O(n) O(n)
      • 空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(每日一题,模拟,leetcode,数据结构,算法)