11. Sorting
Bubble sort
2 for loops
every time compare and swap 2 adjacent elements
find the largest element and move to the end
Time: O(N^2) and space: O(1)
Selection Sort
2 for loops
every loop find the smallest element and move to the beginning
split the arrays into 2 parts, sorted subarray and unsorted subarray
Time: O(N^2) and space: O(1)
Largest Number
给一个int[] nums, 返回一个用nums里的num组成的最大的数
custom sort: basically implement a String comparator to decide which String should come first during concatenation
public String largestNumber(int[] nums) {
String[] arr = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
arr[i] = String.valueOf(nums[i]);
}
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String a, String b) {
String s1 = a + b;
String s2 = b + a;
return s2.compareTo(s1); // reverse order here, so we can do append() later
}
});
if (arr[0].charAt(0) == '0') {
return "0"; // edge case, list of "0"
}
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.toString();
}
Last updated
Was this helpful?