题目链接: Leetcode Weekly Contest 267
1、2073. Time Needed to Buy Tickets
难度:Easy
代码:
class Solution {
public int timeRequiredToBuy(int[] tickets, int k) {
int res=0;
int n=tickets.length;
while(tickets[k]>1){
for(int i=0;i<n;i++){
if(tickets[i]>0){
res++;
tickets[i]--;
}
}
}
for(int i=0;i<=k;i++){
if(tickets[i]>0){
res++;
tickets[i]--;
}
}
return res;
}
}
2、2074. Reverse Nodes in Even Length Groups
难度:Medium
思路:
参考高赞回答。
代码:
/**
* 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 reverseEvenLengthGroups(ListNode head) {
int nodeNumber=1;
ListNode temp=head;
while(temp!=null){
ListNode start=temp;
Stack<Integer> stack=new Stack<>();
int count=0;
while(temp!=null&&count<nodeNumber){
stack.push(temp.val);
temp=temp.next;
count++;
}
if(count%2==0){
while(!stack.isEmpty()){
start.val=stack.pop();
start=start.next;
}
}
nodeNumber++;
}
return head;
}
}
3、2075. Decode the Slanted Ciphertext
难度:Medium
思路:
一种挺有趣的加解密方法,找规律。
代码
class Solution {
public String decodeCiphertext(String encodedText, int rows) {
char[] s=encodedText.toCharArray();
int n=s.length;
int cols=n/rows;
StringBuilder sb=new StringBuilder();
for(int i=0;i<cols;i++){
for(int j=i;j<n;j+=(cols+1)){
sb.append(s[j]);
}
}
int idx=sb.length()-1;
while(idx>=0&&sb.charAt(idx)==' '){
idx--;
}
sb.setLength(idx+1);//删除末尾的所有空格
return sb.toString();
}
}
4、2076. Process Restricted Friend Requests
难度:Hard
思路
参考高赞回答下的评论,用并查集求解。
代码
class Solution {
private int[] parent;
public void UnionFind(int n){
parent=new int[n];
for(int i=0;i<n;i++){
parent[i]=i;
}
}
public int find(int p){
while(parent[p]!=p){
p=parent[p];
}
return parent[p];
}
public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {
int m=requests.length;
UnionFind(n);
boolean[] res=new boolean[m];
for(int i=0;i<m;i++){
int p=find(requests[i][0]);
int q=find(requests[i][1]);
if(p==q){
res[i]=true;
}
else{
boolean valid=true;
for(int[] r:restrictions){
int x=find(r[0]);
int y=find(r[1]);
if((x==p&&y==q)||(x==q&&y==p)){
valid=false;
break;
}
}
if(valid){
res[i]=true;
parent[p]=q;
}
}
}
return res;
}
}