🏠:博客首页: 进击的波吉
📕:今日分享的文章:力扣周赛 第281场 Java题解
💝:坚持刷力扣,分享前三题题解🎈
🌱:Boji 还在努力学算法 ,如有疑问、疏漏之处,请多多指点🙏
☀️:自学成长的路上,感谢大家相伴!No hurry , No Pause !💝
6012. 统计各位数字之和为偶数的整数个数
⭐️主要思路:
送分题,取每个数的各位相加,如果为偶数,则满足条件
class Solution {
public int countEven(int num) {
int res = 0 ;
for (int i = 1 ; i <= num ; i++ ) {
int x= i ;
int cnt = 0 ;
while ( x > 0) {
int t = x %10 ;
x /=10 ;
cnt += t ;
}
if (cnt %2 == 0) res ++ ;
}
return res;
}
}
6013. 合并零之间的节点
⭐️主要思路:
- 创建两个链表,一个存储当前节点 cur ,一个存储结果 res ;
- 分别考虑 val = 0 与 != 0 情况!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeNodes(ListNode head) {
ListNode cur = new ListNode(0) ;
ListNode res = cur ;
head = head.next ;
while (head.next != null ) {
if (head.val == 0 ) {
head = head.next ;
cur.next = new ListNode(0) ;//创建新的空节点
cur = cur.next ; //指向新的空结点
}else {
cur.val += head.val ;
head = head.next ;
}
}
return res ;
}
}
6014. 构造限制重复的字符串
⭐️主要思路:
优先取 最大的字母 当最大字母达到Limit 时,切换为次大的 字母
class Solution {
public String repeatLimitedString(String s, int r) {
int f[] = new int[26];
//记录字符对应的次数
for (char ch : s.toCharArray()) {
f[ch - 'a']++;
}
StringBuilder sb = new StringBuilder();
//按照26个字符的初始顺序 倒叙排列
PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> y[0] - x[0]);
//若存在字符就添加到优先队列中
for (int i = 0; i < 26; i++) {
if (f[i] != 0) pq.add(new int[] { i, f[i] });
}
while (!pq.isEmpty()) {
int curr[] = pq.remove();
boolean rem = false;
while (curr[1] != 0) {
if (rem) {
if (pq.isEmpty()) break;
sb.append((char) (pq.peek()[0] + 'a'));
pq.peek()[1]--;
rem = false;
}
int temp = Math.min(curr[1], r);
int x = temp;
//将次高字符添加进去
while (temp-- > 0) {
sb.append((char) (curr[0] + 'a'));
}
//次高数量减少
curr[1] -= x;
if (!pq.isEmpty() && pq.peek()[1] == 0) pq.remove();
if (curr[1] != 0) rem = true;
}
}
return sb.toString();
}
}