# 0937. Reorder Data in Log Files
###### tags: `Leetcode` `Easy` `Amazon`
Link: https://leetcode.com/problems/reorder-data-in-log-files/
## 思路 $O(MNlogN)$ $O(MlogN)$
自己写一个comparator排序~
**注意:如果是保留原本的顺序是return 0, 不要写return -1**
$M$ is the maximum length of a single log.
The time complexity of the Arrays.sort() is $O(N⋅logN)$, as stated in the API specification. For each invocation of the compare() function, it could take up to $O(M)$ time, since we compare the contents of the logs.
In addition, since the implementation of Arrays.sort() is based on quicksort algorithm whose space complexity is $O(logN)$, assuming that the space for each element is $O(1)$. Since each log could be of $O(M)$ space, we would need $O(M⋅logN)$ space to hold the intermediate values for sorting.
## Code
```java=
class Solution {
public String[] reorderLogFiles(String[] logs) {
Comparator<String> myComp = new Comparator<String>(){
public int compare(String a, String b){
int spaceIndex1 = a.indexOf(' ');
int spaceIndex2 = b.indexOf(' ');
boolean isLetter1 = false;
boolean isLetter2 = false;
if(Character.isLetter(a.charAt(spaceIndex1+1))) isLetter1 = true;
if(Character.isLetter(b.charAt(spaceIndex2+1))) isLetter2 = true;
if(!isLetter1 && !isLetter2){
return 0;
}
else if(isLetter1 && !isLetter2){
return -1;
}
else if(!isLetter1 && isLetter2){
return 1;
}
else{
int preCompute = a.substring(spaceIndex1+1).compareTo(b.substring(spaceIndex2+1));
if(preCompute == 0) return a.substring(0,spaceIndex1).compareTo(b.substring(0,spaceIndex2));
return preCompute;
}
}
};
Arrays.sort(logs, myComp);
return logs;
}
}
```