欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > leetcode 周赛(406)全AC留念

leetcode 周赛(406)全AC留念

2025/2/7 6:50:37 来源:https://blog.csdn.net/weixin_44061648/article/details/140416624  浏览:    关键词:leetcode 周赛(406)全AC留念

纪念第一次 leetcode 周赛(406)全AC
在这里插入图片描述

1.(100352. 交换后字典序最小的字符串) 题目描述:

给你一个仅由数字组成的字符串 s,在最多交换一次 相邻 且具有相同 奇偶性 的数字后,返回可以得到的
字典序最小的字符串
。
如果两个数字都是奇数或都是偶数,则它们具有相同的奇偶性。例如,5 和 9、2 和 4 奇偶性相同,而 69 奇偶性不同。
class Solution {public String getSmallestString(String s) {char[] ch=s.toCharArray();for(int i=1;i<ch.length;i++){if(flag(ch[i])==flag(ch[i-1])&&ch[i]<ch[i-1]){char temp=ch[i];ch[i]=ch[i-1];ch[i-1]=temp;break;}}return new String(ch);}public int flag(char ch){if(ch=='1'||ch=='3'||ch=='5'||ch=='7'||ch=='9'){return 1;}return 0;}
}

2.(100368. 从链表中移除在数组中存在的节点) 题目描述:

给你一个整数数组 nums 和一个链表的头节点 head。从链表中移除所有存在于 nums 中的节点后,返回修改后的链表的头节点。
/*** 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 modifiedList(int[] nums, ListNode head) {Map<Integer,Integer> map=new HashMap<>();for(int num:nums){map.put(num,map.getOrDefault(num,0)+1);}ListNode res=new ListNode(-1,head);ListNode temp=res;while(temp!=null&&temp.next!=null){int num=temp.next.val;if(map.containsKey(num)){temp.next=temp.next.next;}else{temp=temp.next;}}return res.next;}
}

3-4.(100367. 切蛋糕的最小总开销 II) 题目描述:

有一个 m x n 大小的矩形蛋糕,需要切成 1 x 1 的小块。
给你整数 m ,n 和两个数组:
horizontalCut 的大小为 m - 1 ,其中 horizontalCut[i] 表示沿着水平线 i 切蛋糕的开销。
verticalCut 的大小为 n - 1 ,其中 verticalCut[j] 表示沿着垂直线 j 切蛋糕的开销。
一次操作中,你可以选择任意不是 1 x 1 大小的矩形蛋糕并执行以下操作之一:
沿着水平线 i 切开蛋糕,开销为 horizontalCut[i] 。
沿着垂直线 j 切开蛋糕,开销为 verticalCut[j] 。
每次操作后,这块蛋糕都被切成两个独立的小蛋糕。
每次操作的开销都为最开始对应切割线的开销,并且不会改变。
请你返回将蛋糕全部切成 1 x 1 的蛋糕块的 最小 总开销。

第一版(3和4一样,3数据量小 返回值为 int 4 数据量多 返回为 long)

class Solution {public long minimumCost(int m, int n, int[] horizontalCut, int[] verticalCut) {Arrays.sort(horizontalCut);Arrays.sort(verticalCut);int len1=horizontalCut.length;int len2=verticalCut.length;int index1=len1-1;int index2=len2-1;long res=0;int count1=1;int count2=1;while(index1>=0&&index2>=0){if(horizontalCut[index1]>verticalCut[index2]){res+=horizontalCut[index1--]*count1;count2++;}else{res+=verticalCut[index2--]*count2;count1++;}}for(;index1>=0;index1--){res+=horizontalCut[index1]*count1;}for(;index2>=0;index2--){res+=verticalCut[index2]*count2;}return res;}
}

打卡记录留念,之前都是争当三题选手,没想到这次竟然全AC了!!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com