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