力扣第 349 场周赛
题目链接:https://leetcode.cn/contest/weekly-contest-349/
# T1. 既不是最小值也不是最大值
链接:https://leetcode.cn/problems/neither-minimum-nor-maximum/
# 方法一:两次遍历
# 解题思路
- 第一次遍历,求出整个数组的最大值和最小值
 - 第二次遍历,找出首个既不是最大值也不是最小值的数,直接返回
 
# 代码
class Solution {  | |
public int findNonMinOrMax(int[] nums) {  | |
int min = 101;  | |
int max = 0;  | |
for (int num : nums) {  | |
max = Math.max(num, max);  | |
min = Math.min(num, min);  | |
        } | |
for (int num : nums) {  | |
if (num != min && num != max) {  | |
return num;  | |
            } | |
        } | |
return -1;  | |
    } | |
} | 
# 方法二:前三个数进行排序
# 解题思路
对数组的前三个数进行排序,然后取中间的数即可
因为最大值和最小值具有全局性,所以,对前三个数而言,如果包含最大值或者最小值,一定取不到!
# 代码
class Solution {  | |
public int findNonMinOrMax(int[] nums) {  | |
if (nums.length < 3) return -1;  | |
return midVal(nums[0], nums[1], nums[2]);  | |
    } | |
    /** | |
* 求三个数中排序中间的值  | |
*/  | |
private int midVal(int a, int b, int c) {  | |
if (a > b) {  | |
if (b > c) return b;  | |
else return a > c ? c : a;  | |
} else {  | |
if (a > c) return a;  | |
else return b > c ? c : b;  | |
        } | |
    } | |
} | 
# T2. 执行子串操作后的字典序最小字符串
链接:https://leetcode.cn/problems/lexicographically-smallest-string-after-substring-operation/
# 解题思路
要想得到的字符串变小,则【可替换的位置】应该满足
chs[i] > 'a'
贪心:
- 找到第一个【可替换的位置】
- 如果不存在,当前字符串由全 
'a'组成,则只须替换最后一个'a'即可 - 如果存在,则从当前位置往后找一段连续【可替换的位置】,进行全部替换
 
 - 如果不存在,当前字符串由全 
 
# 提交结果

# 代码
class Solution {  | |
public String smallestString(String s) {  | |
        /** | |
* 1. 找到第一个可以替换的位置,即 chs [i] > 'a'  | |
* 2. 从当前位置找到连续的一段可替换的位置  | |
*/  | |
int n = s.length();  | |
int replaceIndex = -1;  | |
for (int i = 0; i < n; ++i) {  | |
if (s.charAt(i) > 'a') {  | |
replaceIndex = i;  | |
break;  | |
            } | |
        } | |
        // 没有替换位置,即全部为 'a',替换最后的 'a' 即可 | |
if (replaceIndex == -1) return s.substring(0, n - 1) + "z";  | |
        // 改成可变字符串 | |
StringBuilder ret = new StringBuilder(s);  | |
while (replaceIndex < n && s.charAt(replaceIndex) > 'a')  | |
ret.setCharAt(replaceIndex, (char) (s.charAt(replaceIndex++) - 1));  | |
return ret.toString();  | |
    } | |
} | 
# T3.
链接: