您的位置:首页 > 其它

LeetCode:第三天

2016-07-11 21:41 429 查看
1、Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],

3

/ \

9 20

/ \

15 7

return its level order traversal as:

[

[3],

[9,20],

[15,7]

]

改进版:

Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree [3,9,20,null,null,15,7],

3

/ \

9 20

/ \

15 7

return its bottom-up level order traversal as:

[

[15,7],

[9,20],

[3]

]

广度优先搜索,这只是我的思路:保存本层的值,同时保存下一层的非空指针。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if(!root)
{
return vector<vector<int>>{};
}
//两个vector,一个目前使用,同时在另一个保存下一层的非空指针
vector<TreeNode*> vTNode1,vTNode2;
vector<vector<int>> res;
vTNode1.push_back(root);
while((!vTNode1.empty())||(!vTNode2.empty()))
{
vector<int> vLevel;
if(!vTNode1.empty())
{
for(const TreeNode* m:vTNode1)
{
vLevel.push_back(m->val);
if(m->left)
{
vTNode2.push_back(m->left);
}
if(m->right)
{
vTNode2.push_back(m->right);
}
}
//清空本层,以便while判断和下次push
vTNode1.clear();
}
else if(!vTNode2.empty())
{
for(const TreeNode* m:vTNode2)
{
vLevel.push_back(m->val);
if(m->left)
{
vTNode1.push_back(m->left);
}
if(m->right)
{
vTNode1.push_back(m->right);
}
}
vTNode2.clear();
}
//一层结束,水平数组存入二维结果
res.push_back(vLevel);
}
//逆序res得到从底部向顶部
vector<vector<int>> res1;
while(!res.empty())
{
res1.push_back(res.back());
res.pop_back();
}
return res1;
}
};


2、Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______6______
/              \
___2__          ___8__


/ \ / \

0 _4 7 9

/ \

3 5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

找最低共同祖先,先判断当前root是否合乎要求,不然就左指针递归(p,q值都小于root值)或右指针递归(都大于)。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(p->val>q->val)//p small,q big
{
swap(q,p);
}
if(root)//如果总是存在的话无需if(root)
{
if(root->val>=p->val&&root->val<=q->val)
{
return root;
}
else if(root->val>q->val)
{
return lowestCommonAncestor(root->left,p,q);
}
else
{
return lowestCommonAncestor(root->right,p,q);
}
}
else
{
return nullptr;
}
}
};


3、Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

两个指针,cur,next指针。重复删掉next即可,delete啊啊!!!

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head)
{
return head;
}
ListNode *cur=head,*nextNode=head->next;
while(nextNode)
{
if(nextNode->val==cur->val)
{
cur->next=nextNode->next;
delete nextNode;
//free(nextNode);//delete!!!
nextNode=cur->next;
}
else
{
cur=cur->next;
nextNode=nextNode->next;
}
}
return head;
}
};


4、Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

写出规律:1 2 3 4 5 6—-1 2 3 5 8 13,可以发现每一层的way是前两层和。递归不成功,超时了,于是该写循环。

class Solution {
public:
int climbStairs(int n) {
if(n==1)
{
return 1;
}
else if(n==2)
{
return 2;
}
// else
// {
//     return climbStairs(n-1)+climbStairs(n-2);
// }
int f1=1,f2=2,fn=0,i=3;
while(i<=n)
{
fn=f1+f2;
f1=f2;
f2=fn;
++i;
}
return fn;
}
};


5、Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]

Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]

Output: 0

In this case, no transaction is done, i.e. max profit = 0.

这个和风口的猪-中国牛市(小米2016校招)很像,但是这个简单一些,只有一次。

建立一个辅助数组就好了。

http://blog.csdn.net/bestzem/article/details/51867015

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size(),minPos=0;
if(len==0)
{
return 0;
}
vector<int> maxProfit(len);
maxProfit[0]=0;//当天可得到最大利润
for(int i=1;i<len;++i)
{
if(prices[i]-prices[minPos]>maxProfit[i-1])
{
maxProfit[i]=prices[i]-prices[minPos];
}
else
{
maxProfit[i]=maxProfit[i-1];
if(prices[i]<prices[minPos])
{
minPos=i;//最小值的索引
}
}
}
return *(max_element(maxProfit.begin(),maxProfit.end()));
}
};


6、Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

首先暴力解法超时,后来想用哈希表,发现可能会有重复的就换了,结果写完了发现怎么可以有重复的。真是想多了。与这个写的有点像。但是总结一下:

A、map,一般不传入算法,因为键值是const的。

B、iter迭代器类指针使用。

http://blog.csdn.net/bestzem/article/details/51858628

简单错误记录(华为2016校招)

class Solution {
public:
static bool compare(pair<int,int> &pa,pair<int,int> &pb)
{
return pa.first<pb.first;
}
vector<int> twoSum(vector<int>& nums, int target) {
int i=0;
vector<pair<int ,int>> vNums;
for(const int &im:nums)
{
vNums.push_back({im,i++});
}
sort(vNums.begin(),vNums.end(),compare);
for(auto iter=vNums.cbegin();iter!=vNums.cend()-1;++iter)
{
for(auto iter1=iter+1;iter1!=vNums.cend();++iter1)
{
if(iter->first+iter1->first==target)
{
if(iter->second<iter1->second)
{
return vector<int>{iter->second,iter1->second};
}
else
{
return vector<int>{iter1->second,iter->second};
}

}
else if(iter->first+iter->first>target)
{
break;
}
}
}
return vector<int>{};

}
};


7、Happy Number

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

找出个位数哪些不是happy number哪些是作为结束条件。

class Solution {
public:
bool isHappy(int n) {
int sum=0;
while(n)
{
sum+=(n%10)*(n%10);
n/=10;
}
if(sum==1||sum==7)
{
return true;
}
else if(sum>=10)
{
return isHappy(sum);
}
else
{
return false;
}
}
};


8、Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

一般情况找出作为结束条件,判断商是否为整数:num/2.0-num/2==0或其中一个转为int既可。

class Solution {
public:
bool isUgly(int num) {
if(num==1||num==2||num==3||num==5)
{
return true;
}
else if(num==0)
{
return false;
}
else if(num/2.0-num/2==0)
{
return isUgly(num/2);
}
else if(num/3.0-num/3==0)
{
return isUgly(num/3);
}
else if(num/5.0-num/5==0)
{
return isUgly(num/5);
}
else
{
return false;
}
}
};


9、House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

辅助数组,可以得到最大的利益,从前往后抢,逐个求出。

class Solution {
public:
int rob(vector<int>& nums) {
int len=nums.size();
if(len<=2)
{
if(len==0)  return 0;
return *(max_element(nums.cbegin(),nums.cend()));
}
vector<int> maxRob(len);
maxRob[0]=nums[0];
maxRob[1]=nums[1];
for(int i=2;i<len;++i)
{
maxRob[i]=nums[i]+*(max_element(maxRob.cbegin(),maxRob.cbegin()+i-1));
}
return *(max_element(maxRob.cbegin(),maxRob.cend()));
}
};


10、Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

一个快指针,一个慢指针,快指针如果赶上了慢指针,则有循环。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)
{
return false;
}
ListNode *fast=head,*slow=head;
while(fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
return true;
}
else if(!fast)
{
return false;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode