归并排序
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public boolean containsDuplicate(int[] nums) {
boolean flag = false;
//练一下归并排序
int[] temp = new int[nums.length];
mergeSort(nums,0,nums.length - 1,temp);
for(int i = 0; i < nums.length - 1; i++){
if(nums[i] == nums[i + 1]){
flag = true;
break;
}
}
return flag;
}
public static void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;// 中间索引
// 向左递归进行分解
mergeSort(arr, left, mid, temp);
// 向右递归进行分解
mergeSort(arr, mid + 1, right, temp);
// 开始合并
merge(arr, left, mid, right, temp);
}
}
public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;// 初始化i,左边有序序列的初始索引
int j = mid + 1;// 初始化j,右边有序序列的初始索引
int t = 0;// temp数组的指针,指向temp数组,让temp后移
// (一)
// 先把左右两边(有序的)数据按照规则填充到temp数组中
// 直到有一边处理完为止
while (i <= mid && j <= right) {
// 如果左边的元素小于右边的,将左边的拷贝到temp数组中
// 同时i和t后移
if (arr[i] < arr[j]) {
temp[t] = arr[i];
t++;
i++;
} else {// 反之,将右边的拷贝到temp中去
temp[t] = arr[j];
t++;
j++;
}
}
// 到这一部,相当于[1, 2, 3, 4, 5, 6, 0 ,0 ]
// 剩余7和8
// (二)
// 把有剩余数据的一边全部拷贝到temp中去
while (i <= mid) {// 如果左边有剩余,将剩余的拷贝到temp中去
temp[t] = arr[i];
t++;
i++;
}
while (j <= right) {// 如果右边有剩余,将剩余的拷贝到temp中去
temp[t] = arr[j];
t++;
j++;
}
// 到这一部,相当于[1, 2, 3, 4, 5, 6, 7, 8],但要拷贝到arr中
// (三)
// 将temp数组中的元素全部拷贝到arr中
// 并不是将所有的数据一下全部拷贝回去
t = 0;
int tempLeft = left;
while (tempLeft <= right) {
// 第一次合并tempLeft = 0,right = 1;//第二次合并:tempLeft = 2,right = 3
// 最后一次:tempLeft = 0,right = 7.
arr[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
}