Question:
Given the array arr [N], for each element of ARR [I] (0 = <I <n), In the ARR [0... the element arr [k] is found in the I-1], where arr [k] satisfies arr [k]> arr [I], and the I-K value is the smallest (that is, the closest ).
It is required that the location of the ARR [k] corresponding to all elements in arr be found in O (n) time.
Ex,
SRC []: 9, 5, 2, 4, 7
DST []:-1, 0, 1, 1, 0
Ideas:
The stack is used to traverse the array from the back to the front. If the elements at the top of the while Stack are smaller than the elements in the array currently traversed, DST is updated and pop is performed.
See the followingCode
Code:
# Include <iostream> <br/> # include <stack> <br/> # include <iterator> </P> <p> using namespace STD; </P> <p> typedef struct withindex <br/>{< br/> int value; <br/> int index; <br/>} withindexst; </P> <p> void nearestnumbergreaterthancurrent (int src [], int DST [], int N) <br/>{< br/> stack <withindexst> m_stack; <br/> for (INT I = n-1; I >=0; I --) <br/>{< br/> while (! M_stack.empty () <br/>{< br/> If (m_stack.top (). value <SRC [I]) <br/>{< br/> DST [m_stack.top (). index] = I; <br/> m_stack.pop (); <br/>}< br/> else <br/> break; <br/>}< br/> withindexst tmpst = {SRC [I], I }; <br/> m_stack.push (tmpst ); <br/>}< br/> DST [0] =-1; <br/>}</P> <p> int main () <br/> {<br/> int SRC [] = {9, 5, 2, 4, 7}; <br/> int nsize = sizeof (SRC) /sizeof (INT); <br/> int * DST = new int [nsize]; <br/> nearestnumbergreaterthancurrent (SRC, DST, nsize ); <br/> copy (SRC, SRC + nsize, ostream_iterator <int> (cout, "/t"); <br/> cout <Endl; <br/> copy (DST, DST + nsize, ostream_iterator <int> (cout, "/t"); <br/> Delete [] DST; <br/> return 0; <br/>}< br/>