LintCode Heapify

原题链接在这里:http://www.lintcode.com/en/problem/heapify/

题目:

Given an integer array, heapify it into a min-heap array.

For a heap array A, A[0] is the root of heap, and for each A[i], A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i].
Clarification

What is heap?

  • Heap is a data structure, which usually have three methods: push, pop and top. where "push" add a new element the heap, "pop" delete the minimum/maximum element in the heap, "top" return the minimum/maximum element.
What is heapify?
  • Convert an unordered integer array into a heap array. If it is min-heap, for each element A[i], we will get A[i * 2 + 1] >= A[i] and A[i * 2 + 2] >= A[i].
What if there is a lot of solutions?
  • Return any of them.
Example

Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.

题解:

从array的中段开始向前对每一个点做sift down.

Time Complexity: O(n). Proof link: http://stackoverflow.com/questions/9755721/how-can-building-a-heap-be-on-time-complexity

Space: O(1).

AC Java:

 1 public class Solution {
 2     /**
 3      * @param A: Given an integer array
 4      * @return: void
 5      */
 6     public void heapify(int[] A) {
 7         if(A == null || A.length == 0){
 8             return;
 9         }
10         for(int i = A.length/2; i>=0; i--){
11             siftDown(A, i);
12         }
13     }
14     
15     private void siftDown(int [] A, int i){
16         int len = A.length;
17         while(i < len){
18             int smallIndex = i;
19             if(2*i+1 < len && A[2*i+1] < A[smallIndex]){
20                 smallIndex = 2*i+1;
21             }
22             if(2*i+2 < len && A[2*i+2] < A[smallIndex]){
23                 smallIndex = 2*i+2;
24             }
25             if(smallIndex == i){
26                 break;
27             }
28             swap(A, i, smallIndex);
29             i = smallIndex;
30         }
31     }
32     
33     private void swap(int [] nums, int i, int j){
34         int temp = nums[i];
35         nums[i] = nums[j];
36         nums[j] = temp;
37     }
38 }

 

posted @ 2017-02-09 05:49  Dylan_Java_NYC  阅读(269)  评论(0编辑  收藏  举报