标签:
Given an integer array, heapify it into a min-heap array.
Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.
O(n) time complexity
What is heap?
public class Solution { /** * @param A: Given an integer array * @return: void */ public void heapify(int[] A) { // write your code here if(A==null || A.length==0) return; for(int i=A.length/2-1;i>=0;i--) { helper(A,i); } } public void helper(int[] A,int i) { //int left=2*i+1>=A.length?Integer.MAX_VALUE:A[2*i+1]; //int right=2*i+2>=A.length?Integer.MAX_VALUE:A[2*i+2]; int left=Integer.MAX_VALUE; int right=Integer.MAX_VALUE; if(2*i+1<A.length) { left=A[2*i+1]; } if(2*i+2<A.length) { right=A[2*i+2]; } //if left is the minimum one in left,righ and A[i].swap it with A[i]; if(left<right && left<A[i]) { A[2*i+1]=A[i]; A[i]=left; helper(A,2*i+1); } else if(right<A[i]) { A[2*i+2]=A[i]; A[i]=right; helper(A,2*i+2); } } }
标签:
原文地址:http://www.cnblogs.com/kittyamin/p/5150132.html