2017.4.27 第一次刷LintCode
1.二叉树最大节点
树的代码大多和递归紧紧结合。注意递归终止的返回条件,以及需要判断返回的节点是否为NULL
class Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode* maxNode(TreeNode* root) {
// Write your code here
if (NULL == root) return NULL;
TreeNode *lmax = maxNode(root->left);
TreeNode *rmax = maxNode(root->right);
if (lmax)
root = lmax->val > root->val? lmax : root;
if (rmax)
root = rmax->val > root->val? rmax : root;
return root;
}
};
2.斐波那契数列
几乎任何一本书里提到这个数列都是要开始讲递归:D,这里如果直接用递归写,会超时。
所以不用递归,直接用循环写。注意这里的n是从1开始的。
class Solution{
public:
/**
* @param n: an integer
* @return an integer f(n)
*/
in fibonacci(int n){
if (n == 1) return 0;
if (n == 2) return 1;
return fibonacci(n-1)+fibonacci(n-2);
}
int fibonacci(int n) {
// write your code here
if (n == 1) return 0;
if (n == 2) return 1;
int a = 0, b = 1;
for (int i = 3; i <= n; i++)
{
int temp = b;
b = a+b;
a = temp;
}
return b;
}
};
3.删除链表中所有值等于val的元素
题目给的head是链表的第一个节点,而不是头结点,链表的删除和插入操作都需要知道其前驱节点。所以声明一个前驱节点pre,初始指向head。由于最后要返回头结点,所以要把初始头节点保存起来,最后返回头结点的next节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
// Write your code here
if (NULL == head) return NULL;
ListNode *pre = new ListNode;
ListNode *ret = new ListNode;
ret = pre;
pre->next = head;
ListNode *curr = head;
while (NULL != curr)
{
while (curr && curr->val != val)
{
pre = curr;
curr = pre->next;
}
if (curr)
{
pre->next = curr->next;
curr = curr->next;
}
}
return ret->next;
}
};
4.整数排序
按照题目要求,写了冒泡和直接插入。平时做算法题大多还是直接用STL里的sort吧。
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
// Write your code here
//choose Bubble sort.
bool exchange = false;
for (int i = 0; i < A.size(); i++)
{
exchange = false;
for (int j = A.size()-1; j > i; j--)
{
if (A[j] < A[j-1])
{
int temp = A[j-1];
A[j-1] = A[j];
A[j] = temp;
exchange = true;
}
}
if (!exchange) break;
}
}
};
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
// Write your code here
//choose Bubble sort.
bool exchange = false;
for (int i = 1; i < A.size(); i++)
{
int j = i-1;
int temp = A[i];
while (j >= 0 && A[j] > temp)
{
A[j+1] = A[j];
j--;
}
A[j+1] = temp;
}
}
};
总结:今天第一次做了LintCode,做了4道入门级别的题目,都是基础题,但是仍然不能做到熟练。有些地方还需要仔细思考,甚至debug。以后开始按tag从易到难开始训练!毕业前第一遍刷完。