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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| class Solution { public List<Integer> sortArray(int[] nums) { sort(nums, 0, nums.length - 1); return IntStream.of(nums).boxed().collect(Collectors.toList()); }
private void merge(int[] nums, int start, int end) { if (start >= end) return; int midIdx = start + (end - start) / 2; merge(nums, start, midIdx); merge(nums, midIdx+1, end); concat(nums, start, midIdx, end); }
private void concat(int[] nums, int start, int midIdx, int end) { int[] tmp = new int[end - start + 1]; int lp = start, rp = midIdx + 1, i = 0;
while (lp <= midIdx && rp <= end) { tmp[i++] = nums[lp] < nums[rp] ? nums[lp++] : nums[rp++]; }
while (lp <= midIdx) { tmp[i++] = nums[lp++]; }
while (rp <= end) { tmp[i++] = nums[rp++]; }
System.arraycopy(tmp, 0, nums, start, tmp.length); }
class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists.length == 0) return null; return merge(lists, 0 , lists.length - 1); }
private ListNode merge(ListNode[] lists, int low, int high) { if (low == high) return lists[low];
int mid = (high - low) / 2 + low;
return mergeLists( merge(lists, low, mid), merge(lists, mid+1, high)); }
public ListNode mergeLists(ListNode node1, ListNode node2) { if (node1 == null) return node2; if (node2 == null) return node1;
if (node1.val < node2.val) { node1.next = mergeLists(node1.next, node2); return node1; } else { node2.next = mergeLists(node1, node2.next); return node2; } } }
private void sort(int[] nums, int start, int end) { if (start >= end) return;
int bIdx = partition(nums, start, end); sort(nums, start, bIdx - 1); sort(nums, bIdx + 1, end); }
private int partition(int[] nums, int start, int end) { int idx = start, base = nums[end];
for (int i = start; i < end; i++) { if (nums[i] < base) { swap(nums, idx++, i); } } swap(nums, idx, end); return idx; }
private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
|