Interview question selection (85): Find the element whose position on the left of each element is closest to the element and greater than the element in the given array arr [N], O (n) Time

Source: Internet
Author: User

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/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.