LeetCode經典題目備忘I

1、有序單鏈錶轉平衡BST

Convert Sorted List to Binary Search Tree           Oct 3'12
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

時間複雜度O(n)

C++實現:

BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
    if (start > end) return NULL;
    // same as (start+end)/2, avoids overflow
    int mid = start + (end - start) / 2;
    BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
    BinaryTree *parent = new BinaryTree(list->data);
    parent->left = leftChild;
    list = list->next;
    parent->right = sortedListToBST(list, mid+1, end);
    return parent;
}

BinaryTree* sortedListToBST(ListNode *head, int n) {
    return sortedListToBST(head, 0, n-1);
}

2、最長連續序列

Longest Consecutive Sequence        Feb 14

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.

時間複雜度O(n)

Java實現:

public int findLongestConsequence(int[] a) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    int max = 1;
    for (int i : a) {
        if (map.containsKey(i)) continue;
        map.put(i, 1);
        if (map.containsKey(i - 1)) {
            max = Math.max(max, merge(map, i-1, i));
        }
        if (map.containsKey(i + 1)) {
            max = Math.max(max, merge(map, i, i+1));
        }
    }
    return max;
}

private int merge(HashMap<Integer, Integer> map, int left, int right) {
    int upper = right + map.get(right) - 1;
    int lower = left - map.get(left) + 1;
    int len = upper - lower + 1;
    map.put(upper, len);
    map.put(lower, len);
    return len;
}

3、O(1)空間複雜度下,層次遍歷二叉樹

Populating Next Right Pointers in Each Node II      Oct 28 '12

Follow up for problem "Populating Next Right Pointers in Each Node".
Given a binary tree

struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
 }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
The given tree could be any binary tree.
For example,
Given the following binary tree,
         1
       /   \
      2    3
     /   \     \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /     \
      2 -> 3 -> NULL
     /   \       \
    4-> 5 -> 7 -> NULL

時間複雜度O(n),空間複雜度O(1)

C++實現:

void connect(TreeLinkNode * n) {
    while (n) {
        TreeLinkNode * next = NULL; // the first node of next level
        TreeLinkNode * prev = NULL; // previous node on the same level
        for (; n; n=n->next) {
            if (!next) next = n->left?n->left:n->right;

            if (n->left) {
                if (prev) prev->next = n->left;
                prev = n->left;
            }
            if (n->right) {
                if (prev) prev->next = n->right;
                prev = n->right;
            }
        }
        n = next; // turn to next level
    }
}

4、矩陣中找最大的(滿)矩形

Maximal Rectangle    Apr 24 '12

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

時間複雜度O(m * n)

ps:可參考本人的另一篇博文《柱狀圖中找最大矩形 & 矩陣中找最大的僅含相同值的矩形區域》

C++實現:

int largestRectArea(vector<int> &height) {
	stack<int> p;
	int i = 0, res = 0;
	height.push_back(0);
	while(i < height.size()) {
		if(p.empty() || height[p.top()] <= height[i])
		p.push(i++);
		else {
			int t = p.top();
			p.pop();
			res = max(res, height[t] * (p.empty() ? i : i - p.top() - 1 ));        
		}
	}
	height.pop_back();
	return res;
}
int maximalRectangle(vector<vector<char> > &matrix) {
	int row = matrix.size();
	int column = 0;
	if(row == 0 || (column = matrix.front().size()) == 0)
		return 0;
	int res = 0;
	vector<int> height(column, 0);
	for(int ri = 0; ri < row; ++ri){
		for(int ci = 0; ci < column; ++ci)
			height[ci] = (matrix[ri][ci] == '0' ? 0 : height[ci] + 1);
		res = max(res, largestRectArea(height));
	}
	return res;
}

5、旋轉數組的二分查找

Search in Rotated Sorted Array II    Apr 20 '12

Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
Note: Duplicates in the array are allowed?
Write a function to determine if a given target is in the array.

平均時間複雜度O(logN),最壞時間複雜度O(N)

C++實現:

bool search(int A[], int n, int key) {
    int l = 0, r = n - 1;
    while (l <= r) {
        int m = l + (r - l)/2;
        if (A[m] == key) return true; //return m in Search in Rotated Array I
        if (A[l] < A[m]) { //left half is sorted
            if (A[l] <= key && key < A[m])
                r = m - 1;
            else
                l = m + 1;
        } else if (A[l] > A[m]) { //right half is sorted
            if (A[m] < key && key <= A[r])
                l = m + 1;
            else
                r = m - 1;
        } else l++;
    }
    return false;
}










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章