leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III
1、
String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical
digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
分析:此题非经常见,此题的错误处理是比較简单的。假设不能转换则变为0。注意溢出问题时先使用long long来保存结果,然后做转换,而不是long,非常多系统下long int和int的值范围是同样的。
代码例如以下:
class Solution {
public:
int atoi(const char *str) {
if(!str){
return 0;
}
while(*str==' '){
++str;
}
bool minus = false;
if(*str == '-'){
minus = true;
++str;
}else if(*str == '+'){
++str;
}
long long result = 0;
while(*str!='\0'){
if(*str <= '9' && *str >= '0'){
result = result*10+*str-'0';
if( !minus && result>INT_MAX ){
return INT_MAX;
}else if( minus && -result < INT_MIN ){
return INT_MIN;
}
}else{
break;
}
++str;
}
return minus==true? -(int)result:(int)result;
}
};
2、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.
分析:求一个股票的最大收益。这个题在阿里面试过程中遇到过。只是做了变形,后来才发现leetcode中类似的题目。之前有同学去面试也出过类似的题目。求一个数组前面数字减去后面数字的绝对值的最大值,这都是一类题目,解题思路差点儿相同。
解题思路:保存一个截止到i的股票价格的最小值和股票收益的最大值,假设prices[i]>股票价格的最小值,则有收益,比較此时收益和最大收益,更新最大收益。假设prices[i]<i前面股票价格的最小值,则更新最小值。
代码例如以下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()<2){
return 0;
}
int maxProfit = 0;
int tempProfit = 0;
int minPrice = 0;
for(int i=0; i<prices.size(); ++i){
if( i==0 ){
minPrice = prices[i];
}
if( prices[i] < minPrice ){
minPrice = prices[i];
}else{
tempProfit = prices[i] - minPrice;
if(tempProfit > maxProfit){
maxProfit = tempProfit;
}
}
}
return maxProfit;
}
};
3、Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell
the stock before you buy again).
分析:此题和上一题是一系列。可是能够多次买入卖出,感觉有点不知道怎样求解,但细致想,画出波浪线时,能够想到是求每一个上升阶段的最大最小差值的和,想到这里就不难实现了。注意各种參数。
代码例如以下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if( prices.size()<2 ){
return 0;
}
int maxProfit = 0; //最大收益
int preProfit = 0; //上一上升阶段的收益
int curMinPrice = 0; //当前最小值
int curMaxProfit = 0; //当前最大收益
int buyIndex = 0; //上次购买的时间
for(int i=0; i<prices.size();++i){
if(i==0){
curMinPrice = prices[i];
buyIndex = i;
continue;
}
if(prices[i] < prices[i-1]){ //在下降阶段
if(buyIndex != i-1){ //假设是第一个下降点
curMinPrice = prices[i];
curMaxProfit = 0;
maxProfit += preProfit;
buyIndex = i;
}else{
if(prices[i] < curMinPrice){ //在下降阶段
curMinPrice = prices[i];
buyIndex = i;
}
}
}else{ //一直在上升阶段
preProfit = prices[i] - curMinPrice;
if(preProfit > curMaxProfit){
curMaxProfit = preProfit;
}
if(i == prices.size()-1){
maxProfit += preProfit;
}
}
}
return maxProfit;
}
};
4、Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:此题和前面的类似。可是不同的是最多买两次的收益最大,首先想到的是将数组从0到数组末尾点N分别分成两半,计算分别计算左右的最大盈,利。将其加和,从这N个数中取最大的就为最多两次收益最大的值。可是这样求解局部最大盈利时子问题反复求解,想到利用空间换时间的方法,利用数组保存前一半的最大盈利,第i+1个点的盈利能够利用i个点的盈利求得;然后从后往前遍历,求i点后的最大盈利,同一时候将i点的最大盈利与前面数组i-1的位置元素相加(为啥是i-1位置呢。由于同一个点不能同一时候买入卖出),更新总最大盈利。
代码例如以下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int length = prices.size();
if(length<2){
return 0;
}
int maxProfit = 0; //用数组记录从開始到每一个元素位置的最大收益
int* profit1 = new int[length];
int buyPrice = 0;
int tempProfit = 0;
for(int i=0; i<length; ++i){
if(i==0){
profit1[i] = 0;
buyPrice = prices[i];
continue;
}
if(prices[i] > buyPrice){//假设大于前面的最小值
tempProfit = prices[i] - buyPrice;
if(tempProfit > profit1[i-1]){
profit1[i] = tempProfit; //更新最大盈利
}else{
profit1[i] = profit1[i-1];
}
}else{ //假设小于前面的最小值,则更新最小值
buyPrice = prices[i];
profit1[i] = profit1[i-1];
}
}
//从后往前遍历,计算每一个元素后的最大收益
int sellPrice = 0;
int postMaxProfit = 0;
int tempPrice = 0;
for(int i=length-1; i>0; --i){
if(i==length-1){
sellPrice = prices[i];
maxProfit = profit1[i];
continue;
}
if(prices[i]<sellPrice){
tempPrice = sellPrice - prices[i];
if(tempPrice > postMaxProfit){
postMaxProfit = tempPrice;
}
}else{
sellPrice = prices[i];
}
if(postMaxProfit+profit1[i-1] > maxProfit){
maxProfit = postMaxProfit+profit1[i-1];
}
}
delete[] profit1;
return maxProfit;
} };
leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III的更多相关文章
- LeetCode:Best Time to Buy and Sell Stock I II III
LeetCode:Best Time to Buy and Sell Stock Say you have an array for which the ith element is the pric ...
- LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV
Best Time to Buy and Sell Stock I 题目链接 题目要求: Say you have an array for which the ith element is the ...
- [LeetCode] 递推思想的美妙 Best Time to Buy and Sell Stock I, II, III O(n) 解法
题记:在求最大最小值的类似题目中,递推思想的奇妙之处,在于递推过程也就是比较求值的过程,从而做到一次遍历得到结果. LeetCode 上面的这三道题最能展现递推思想的美丽之处了. 题1 Best Ti ...
- [Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III
Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a gi ...
- Best Time to Buy and Sell Stock I,II,III [leetcode]
Best Time to Buy and Sell Stock I 你只能一个操作:维修preMin拍摄前最少发生值 代码例如以下: int maxProfit(vector<int> & ...
- Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)
Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...
- 【leetcode】String to Integer (atoi)
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- [leetcode] 8. String to Integer (atoi) (Medium)
实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...
- Leetcode 8. String to Integer (atoi)(模拟题,水)
8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...
随机推荐
- One simple health check for oracle with sql
There are some sqls which is used for check the oracle database's health condition. ------numbers of ...
- [REST Jersey] @QueryParam Demo
This demo sourced from the jersey tutor. https://jersey.java.net/documentation/latest/jaxrs-resource ...
- Spring通过工厂创建实例的注意事项
假设第三方(or别的team)提供一个工厂类(此类是不能够改动的.往往以jar包形式提供的),须要供给我们项目来使用. 可是我们自己的项目使用了spring来配置,所以我们当然希望可以通过spring ...
- AVL树的插入删除查找算法实现和分析-1
至于什么是AVL树和AVL树的一些概念问题在这里就不多说了,下面是我写的代码,里面的注释非常详细地说明了实现的思想和方法. 因为在操作时真正需要的是子树高度的差,所以这里采用-1,0,1来表示左子树和 ...
- 图片组件——axure线框图部件库介绍
我们在后面的组件使用中,都统一使用"从部件区域拖拽图片组件到页面区域中" 1. 图片载入 1.1 将图片组件拖拽到页面区域 1.2 双击图片组件 1.3 选择合适图片,点击打开 1 ...
- 大数据高并发系统架构实战方案(LVS负载均衡、Nginx、共享存储、海量数据、队列缓存)
课程简介: 随着互联网的发展,高并发.大数据量的网站要求越来越高.而这些高要求都是基础的技术和细节组合而成的.本课程就从实际案例出发给大家原景重现高并发架构常用技术点及详细演练. 通过该课程的学习,普 ...
- zoj1028-Flip and Shift
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=28 题意:有相互交叉的黑白两种颜色的小球,每一个小球每次可以跳两格:问你是否可以 ...
- C++ template error: undefined reference to XXX
一般来说,写C++程序时推荐“类的声明和实现分离”,也就是说一个类的声明放在example.h文件中,而这个类的实现放在example.cpp文件中,这样方便管理,条理清晰. 但是如果类的声明用到了模 ...
- Java中怎么控制线程訪问资源的数量
在API中是这样来描写叙述Semaphore 的 Semaphore 通经常使用于限制能够訪问某些资源(物理或逻辑的)的线程数目. 一个计数信号量.从概念上讲,信号量维护了一个许可集.如有必要,在许可 ...
- 怎样将Emoj表情插入mysql5.6数据库__python+mysqldb
废话不多说,相信看到这里的看客已经看过非常多配置文件的设置方法.可是问题还是没有解决.本文就具体记录一下我的解决方法吧. 我的环境:mysql5.6+python2.7.3+MySQLdb1.2.4 ...