包含min函數的棧
定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。
注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。
class Solution {
public:
stack<int> s1,s2;
void push(int value){
s1.push(value);//s1記錄所有的數字
if(s2.empty()) s2.push(value);//如果s2是空的,先push進去
else if(value<=s2.top()) s2.push(value);
//如果這個value小於等於s2的棧首,push進去,s2一定是遞減的,s2的棧首一定是最小的
}
void pop(){
if(s1.top()==s2.top()) s2.pop();//如果兩個棧首相等,s2出棧,表明出棧的這個是最小的
s1.pop();//s1始終要出棧
}
int top(){
return s1.top();
}
int min(){
return s2.top();
}//s2維護的是min,
};
69. x 的平方根
難度簡單363收藏分享切換爲英文關注反饋
實現 int sqrt(int x)
函數。
計算並返回 x 的平方根,其中 x 是非負整數。
由於返回類型是整數,結果只保留整數的部分,小數部分將被捨去。
示例 1:
輸入: 4 輸出: 2
示例 2:
輸入: 8 輸出: 2 說明: 8 的平方根是 2.82842..., 由於返回類型是整數,小數部分將被捨去。
class Solution {
public:
/*1.從1枚舉,注意 long long int tmp=(long long int)(i+1)*(long long int)(i+1);
執行用時 :52 ms, 在所有 C++ 提交中擊敗了5.06%的用戶
內存消耗 :5.9 MB, 在所有 C++ 提交中擊敗了100.00%的用戶*/
int mySqrt1(int x) {
int res=0;
for(int i=1;i<=x;i++){
if(i*i==x){
res=i; break;
}
else if(i*i<x){
long long int tmp=(long long int)(i+1)*(long long int)(i+1);
if(tmp>(long long int)x){
res=i; break;
}
}
}
return res;
}
/*2.袖珍計算器算法,使用指數函數exp和對數函數ln代替平方根函數的方法,根號x=x^1/2=(e^lnx)^1/2=e^(1/2*lnx)
執行用時 :4 ms, 在所有 C++ 提交中擊敗了70.20%的用戶
內存消耗 :6.3 MB, 在所有 C++ 提交中擊敗了100.00%的用戶*/
int mySqrt2(int x){
if(x==0) return 0;
int res=exp(0.5*log(x));
if((long long) (res+1)*(res+1) <=x) return res+1;
return res;
}
/*3.二分查找,
執行用時 :0 ms, 在所有 C++ 提交中擊敗了100.00%的用戶
內存消耗 :5.8 MB, 在所有 C++ 提交中擊敗了100.00%的用戶
*/
int mySqrt3(int x){
int l=0,r=x,res=-1;
while(l<=r){
int mid=l+(r-l)/2;
if((long long)mid*mid<=x){
res=mid;
l=mid+1;
}else r=mid-1;
}
return res;
}
/*4.牛頓迭代,快速求解函數零點
https://leetcode-cn.com/problems/sqrtx/solution/x-de-ping-fang-gen-by-leetcode-solution/*/
};