You are given a 0-indexed integer array nums
and an integer target
.
You need to determine the indices of the array where the value equals the target after sorting the array in non-decreasing order. Return these indices in the form of a list. If there are no such indices, return an empty list.
nums
can have length [1, 100]
.nums
is an integer within the range [1, 100]
.target
is not present in the array at all?
Let’s write the Python function to achieve this:
def targetIndices(nums, target):
# Step 1: Sort the array
nums.sort()
# Step 2: Find the indices of the target value
result = []
for i, num in enumerate(nums):
if num == target:
result.append(i)
return result
O(n log n)
time, where n
is the number of elements in nums
.O(n)
time.Thus, the total time complexity of the solution is O(n log n)
.
Let’s test the function with an example:
nums = [1, 2, 5, 2, 3]
target = 2
print(targetIndices(nums, target)) # Output should be [1, 2]
This example assumes the sorted array is [1, 2, 2, 3, 5]
, and the target value 2
appears at indices 1
and 2
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?