牛客20、5(归并排序)
20数组中的逆序对
代码
public class Solution { int count = 0; public int InversePairs(int [] array) { if(array.length < 2) return 0; int[] result = new int[array.length]; mergeSort(array, 0, array.length - 1, result); return count; } public void mergeSort(int[] array, int left, int right, int[] result) { if (left == right) return; int mid = left + (right - left) / 2; mergeSort(array, left, mid, result); mergeSort(array, mid + 1, right, result); merge(array, left, right, result); } public void merge(int[] array, int start, int end, int[] result) { int end1 = (start + end) / 2; int start2 = end1 + 1; int index1 = start; int index2 = start2; while (index1 <= end1 && index2 <= end) { if (array[index1] <= array[index2]) result[index1 + index2 - start2] = array[index1++]; else { result[index1 + index2 - start2] = array[index2++]; count += start2 - index1; count %= 1000000007; } } while (index1 <= end1) result[index1 + index2 - start2] = array[index1++]; while (index2 <= end) result[index1 + index2 - start2] = array[index2++]; while (start <= end) array[start] = result[start++]; } }
5合并k个已排序的链表
public class Solution { public ListNode mergeKLists(ArrayList<ListNode> lists) { return divideMerge(lists, 0, lists.size() - 1); } public ListNode divideMerge(ArrayList<ListNode> lists, int left, int right) { if (left > right) { return null; } else if (left == right) { return lists.get(left); } int mid = (left + right) / 2; return Merge(divideMerge(lists, left, mid), divideMerge(lists, mid + 1, right)); } public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) return list2; if (list2 == null) return list1; ListNode head = new ListNode(0); ListNode cur = head; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { cur.next = list1; list1 = list1.next; } else { cur.next = list2; list2 = list2.next; } cur = cur.next; if (list1 != null) { cur.next = list1; } else { cur.next = list2; } } return head.next; } }