升级的网站显示什么,微信小程序开发教程书籍,手机营销网站,电子商务网站建设内涵给你一个整数数组 nums#xff0c;请你将该数组升序排列。
输入#xff1a;nums [5,2,3,1]
输出#xff1a;[1,2,3,5]
输入#xff1a;nums [5,1,1,2,0,0]
输出#xff1a;[0,0,1,1,2,5]
思路直接看我录制的视频吧 算法-堆排序_哔哩哔哩_bilibili
实现代码如下所示请你将该数组升序排列。
输入nums [5,2,3,1]
输出[1,2,3,5]
输入nums [5,1,1,2,0,0]
输出[0,0,1,1,2,5]
思路直接看我录制的视频吧 算法-堆排序_哔哩哔哩_bilibili
实现代码如下所示
class Solution {public int[] sortArray(int[] nums) {if (nums null || nums.length 1) {return nums;}headSort(nums);return nums;}private void headSort(int[] nums) {for (int i (nums.length - 1) / 2; i 0; i--) {adjustHead(nums, i, nums.length);}for (int i nums.length - 1; i 0; i--) {int temp nums[i];nums[i] nums[0];nums[0] temp;adjustHead(nums, 0, i);}}private void adjustHead(int[] nums, int parent, int length) {int temp nums[parent];int maxChildIndex parent * 2 1;while (maxChildIndex length) {int rightChild maxChildIndex 1;if (rightChild length nums[rightChild] nums[maxChildIndex]) {maxChildIndex;}if (maxChildIndex length nums[maxChildIndex] temp) {break;}nums[parent] nums[maxChildIndex];parent maxChildIndex;maxChildIndex maxChildIndex * 2 1;}nums[parent] temp;}
}