Statement▼
You are given a 0-indexed array of positive integers, nums, and a value, target. The target represents an index nums[i] == target.
Your task is to return a list of indexes of nums where the value equals target after sorting the array in nondecreasing order. If no such indexes exist, return an empty list. Ensure the returned list is sorted in increasing order.
Constraints:
1≤ nums.length≤100 1≤ nums[i],target≤100
Solution
In this problem, we will utilize the Sort and Search pattern to find the indexes of a target value in a sorted array. The core idea is to first sort the input array, nums, in nondecreasing order, which ensures that we can easily identify the positions of the target value. After sorting, we will search through the sorted array to collect the indexes where target appears. This approach combines sorting to organize the data with a linear search to gather the desired indexes, making it both straightforward and efficient.
Let’s break down the algorithm steps involved in the solution:
Sorting the array:
We first sort the input array
numsto ensure that the target value’s positions can be easily identified after the array is in a nondecreasing order.
Identifying the target indexes:
After sorting the array, we create an empty array
resultthat stores the matching values' indexes.Next, we find the indexes of the
targetvalue in the sorted array. We do this by iterating through the sorted array and checking where the value matches thetarget.If it does, we store the index at which the
targetappears in theresultarray.
Returning the result:
After iterating through
nums, we returnresultcontaining indexes at which thetargetappears in the sortednumsarray.
Let’s look at the following illustration to get a better understanding of the solution: