开篇分享
⭐️本次参加双周赛只AC一题,2、3两题 思路有点乱,在临界判断上总是卡壳,看到歪果仁的题解,还是被巧妙的思路惊叹到!!!还是坚持把前三题题解写完!🏃
5984. 拆分数位后四位数字的最小和
主要思路
:取出每位数,在数组中排序,将最小的两个放在十位,最大的两个放在个位,很简单就对了!😋
class Solution {
public int minimumSum(int num) {
int[] res = new int[4] ;
for (int i =0; i< 4; i++) {
int x = num % 10 ;
res[i] = x ;
num /=10 ;
}
Arrays.sort(res, 0, 4) ;
return (res[0]*10 + res[3] + res[1]*10 + res[2]) ;
}
}
5985. 根据给定数字划分数组
思路一
:本题主要是排序后。保持原有的相对位置,可以遍历枚举,代码很简洁!
时间复杂度 :O(n) ;
class Solution {
public int[] pivotArray(int[] nums, int pivot) {
int n = nums.length ;
int i = 0;
int[] res = new int[n] ;
for (int num : nums)
if (num < pivot)
res[i++] = num ;
for (int num : nums)
if (num == pivot)
res[i++] = num ;
for (int num : nums)
if ( num > pivot)
res[i++] = num ;
return res ;
}
}
思路二
: 三指针的思路!
class Solution {
public int[] pivotArray(int[] nums, int pivot) {
int n = nums.length ;
int low = 0 ;
int same = 0 ;
int high ;
for (int num : nums) {
if (num < pivot) low++ ;
else if (num == pivot) same++ ;
}
high = low + same ; //记录大于 pivot的开始
same =low ; //记录 等于pivot
low = 0 ;
int[] res = new int[n] ;
for (int num : nums) {
if (num < pivot) res[low++] = num ;
else if (num == pivot) res[same++] = num ;
else res[high++] = num ;
}
return res ;
}
}
5986. 设置时间的最少代价
主要思路
:
- 因为秒数的范围 为 [0, 99 ],需要分两类讨论:
a. mins = targetSeconds / 60, secs = targetSeconds % 60 ;
b. mins = targetSeconds / 60 - 1 , secs = targetSeconds % 60 +60 ; - 为了避免生成前置0,将 整数 min*100 + secs 换算成 秒表显示示数!
class Solution {
public int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {
int secs = targetSeconds %60 ;
int mins = targetSeconds /60 ;
int res1 = cal(startAt, moveCost, pushCost ,mins, secs) ;
int res2 = cal(startAt, moveCost, pushCost ,mins-1, secs+60 ) ;
return Math.min(res1, res2) ;
}
public int cal(int startAt, int moveCost, int pushCost, int mins,int secs) {
// 非法输入
if (mins > 99 || mins < 0 || secs >99|| secs< 0 ) {
return Integer.MAX_VALUE ;
}
int res= 0 ;
// 将整数转化为字符串处理
String str = Integer.toString(mins*100 + secs) ;
char curr = (char)( startAt + '0' );
for (int i = 0; i < str.length(); i++) {
// 若字符相同,只需要pushCost
if (str.charAt(i) == curr) res +=pushCost ;
else{
res += pushCost + moveCost ;
curr = str.charAt(i) ; //更新现在的字符
}
}
return res ;
}
}