← 返回 snowflake 的题目列表Distance from Each 1 to the Nearest 2 in an Array
类型:online_judge
Problem: Distance from Each 1 to the Nearest 2 in an Array
You are given an array arr of length n. Each element is one of 0, 1, or 2.
For every position whose value is 1, compute its distance to the nearest position whose value is 2. The distance between positions i and j is defined as |i - j|.
Output the distances for all 1s in left-to-right order.
If there is no 2 in the array, output -1 for every 1.
If there is no 1, output an empty line.
Input Format
n
arr[0] arr[1] ... arr[n-1]
Output Format
distances for each 1, separated by spaces
Constraints
1 <= n <= 200000
arr[i] is one of 0, 1, or 2
Example
Input:
7
1 0 2 0 1 2 1
Output:
2 1 1
Explanation:
The 1 at index 0 has nearest 2 at distance 2;
The 1 at index 4 has nearest 2 at distance 1;
The 1 at index 6 has nearest 2 at distance 1.
Example
Input
7
1 0 2 0 1 2 1
Output
2 1 1