Problem: Given an array of integers, find the nearest smaller number for every integer on its left side.
Solution: Use stack.
Implementation:
void printNearestSmaller(int arr[], int len)
{
if(len <= 0)
return;
std::stack<int> st;
for(int i = 0; i < len; ++i)
{
while(!st.empty() && st.top() >= arr[i])
st.pop();
if(st.empty())
std::cout<<"-\t";
else
std::cout<<st.top()<<'\t';
st.push(arr[i]);
}
std::cout<<std::endl;
}
Complexity: O(n)
No comments:
Post a Comment