【数据结构与算法经典问题解析--java语言描述】_第10章_学习记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37770023/article/details/82934959

【数据结构与算法经典问题解析--java语言描述】_第21章_学习记录

排序的相关问题:

問題01: 給定含有重複元素的n個數的數組A[0, .. n-1].給出算法,檢查是否存在重複元素。假設不允許使用額外的空間
 (即可以使用臨時變量,O(1)存儲空間)

package p10;

/**
 * 問題01: 給定含有重複元素的n個數的數組A[0, .. n-1].給出算法,檢查是否存在重複元素。假設不允許使用額外的空間
 * (即可以使用臨時變量,O(1)存儲空間)
 * @author Guozhu Zhu
 * @date 2018/10/3
 * @version 1.0
 *
 */
public class Demo01 {
	
	/* ========== Test ========== */
	public static void main(String[] args) {
		int[] arr = {1, 3, 2, 2, 2, 4, 5, 6};
		boolean res = checkDuplicateInArray(arr);
		System.out.println(res);
	}
    
	//暴力破解, 時間O(n)=n^2, 空間O(n)=1;
	public static boolean checkDuplicateInArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			for (int j = i+1; j < arr.length; j++) {
				if (arr[i] == arr[j]) {
					return true;
				}
			}
		}
		return false;
	}

}

问题2:能否降低问题1的时间复杂度

package p10;

/**
 * 問題02: 降低問題01的時間複雜度
 * @author Guozhu Zhu
 * @date 2018/10/3
 * @version 1.0
 *
 */
public class Demo02 {
	
	/* ========== Test ========== */
	public static void main(String[] args) {
		int[] arr = {1, 3, 2, 4, 2, 5, 6};
		boolean res = checkDuplicateInArray(arr);
		System.out.println(res);
	}
	
	public static boolean checkDuplicateInArray(int[] arr) {
		HeapSort(arr);    //先進行排序
		for (int i = 0; i < arr.length-1; i++) {
			if (arr[i] == arr[i+1]) {
				return true;
			}
		}
		return false;
	}
	
	//堆排序
	public static void HeapSort(int[] arr) {
		int len = arr.length;
		for (int i = (int) Math.floor(len/2); i >= 0; i--) {
			downAdjust(arr, i, arr.length-1);
		}
		for (int i = arr.length-1; i > 0; i--) {
			swap(arr, 0, i);
			downAdjust(arr, 0, i-1);
		}
	}
	
	public static void downAdjust(int[] arr, int parentIndex, int length) {
		int temp = arr[parentIndex];
		int childIndex = parentIndex*2+1;
		while (childIndex <= length) {
			if (childIndex+1 <= length && arr[childIndex+1] > arr[childIndex]) {
				childIndex++;
			}
			if (temp > arr[childIndex]) {
				break;
			}
			arr[parentIndex] = arr[childIndex];
			parentIndex = childIndex;
			childIndex = childIndex*2;
		}
		arr[parentIndex] = temp;
	}
	
	public static void swap(int[] arr, int i, int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_37770023/article/details/82934959