Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

937. Reorder Data in Log Files

Posted on 2020-07-01 | Edited on 2021-01-22

LeetCode

Approach 1: Custom Sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public String[] reorderLogFiles(String[] logs) {
Arrays.sort(logs,(log1,log2)->{
String[] split1=log1.split(" ",2);
String[] split2=log2.split(" ",2);
boolean isDigit1=Character.isDigit(split1[1].charAt(0));
boolean isDigit2=Character.isDigit(split2[1].charAt(0));
if(!isDigit1&&!isDigit2){
int cmp=split1[1].compareTo(split2[1]);
if(cmp==0) return split1[0].compareTo(split2[0]);
else return cmp;
}
return isDigit1?(isDigit2?0:1):-1; /* 1: descending order, -1: ascending order*/
});
return logs;
}
}

Approach 2: TreeMap + PriorityQueue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public String[] reorderLogFiles(String[] logs) {
List<String> ls=new ArrayList<>();

Map<String,Queue<String>> map=new TreeMap<>();
for(String log:logs){
String[] split=log.split(" ",2);
String id=split[0];
String content=split[1];
if(Character.isLetter(content.charAt(0))){
if(!map.containsKey(content)){
map.put(content,new PriorityQueue<String>());
}
map.get(content).offer(id);
}else{
ls.add(log);
}
}

int idx=0;
for(String content:map.keySet()){
Queue<String> q=map.get(content);
while(!q.isEmpty()){
String id=q.poll();
ls.add(idx,id+" "+content);
idx++;
}
}
return ls.toArray(new String[0]);
}
}

<1…111112113…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%