You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices ofnums after sortingnumsin non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Example 1:
Input: nums = [1,2,5,2,3], target = 2 Output: [1,2] Explanation: After sorting, nums is [1,2,2,3,5]. The indices where nums[i] == 2 are 1 and 2.
Example 2:
Input: nums = [1,2,5,2,3], target = 3 Output: [3] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 3 is 3.
Example 3:
Input: nums = [1,2,5,2,3], target = 5 Output: [4] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 5 is 4.
for i in range(target_index - 1, -1, -1): if sorted_nums[i] == target: res.append(i) res = res[::-1] for i in range(target_index, len(sorted_nums)): if sorted_nums[i] == target: res.append(i) return res
deftargetIndices(self, nums: List[int], target: int) -> List[int]: sorted_nums = sorted(nums) target_upper_index = self.last_position(sorted_nums, target) target_lower_index = self.first_position(sorted_nums, target) res = [i for i in range(target_lower_index, target_upper_index + 1)] return [] if target_upper_index == -1else res
deffirst_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target < nums[mid]: end = mid elif target > nums[mid]: start = mid else: end = mid
if nums[start] == target: return start elif nums[end] == target: return end else: return-1
deflast_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target < nums[mid]: end = mid elif target > nums[mid]: start = mid else: # Depends on the target on the right side or left side. For fist pos, use end = mid start = mid
if nums[end] == target: return end elif nums[start] == target: return start else: return-1