Twitter OA prepare:visit element of the array

Source: Internet
Author: User

A zero-indexed array a consisting of N integers is viven. We visit the Indexs of the array in the following. In the first step we visit the index 0; In every subsequent step we move from the visited index K to the Index:m= K +A[k];p rovided M is within the array bounds. Otherwise, K is the last index visited. Write a Funciton:intSolution (intA[],intN); that, given an array A, returns the number of indexes that cannot is visited by the described procedure. For example, forThe array:a[0] = 1a[1] = 2a[2] = 3Only index2 cannot be visited, so the answer is 1. for the array:a[0] = 3a[1] = 5a[2] = 0a[3] = 1a[4] = 3Indexes1 and 4 cannot be visited, so the answer is 2. Assume That:n is an integer within the range [0...200,000];each element of array A is an integer within the range [-1,000,000...1,000,000]complexity:expected Worst- CaseTime complexity is O (nlog (N)); expected worst- CaseSpace complexity is O (N*log (N)), beyond input storage (not counting the storage required forinput arguments). Elements of input arrays can be modified.

Analysis: is to set up a Boolean array to record the access of each element in an array, to stop visiting when encountering an element, and to return the number of unreachable nodes.

1  Public intVisiting (int[] A,intN) {2     if(a==NULL|| a.length==0)return0;3     intCur = 0;4     intCount = 0;5     Boolean[] visited =New Boolean[N];6      while(cur>=0 && cur<a.length &&!)Visited[cur]) {7Visited[cur] =true;8cur = cur +A[cur];9count++;Ten     } One     returnN-count; A}

Twitter OA prepare:visit element of the array

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.