Skip to content

Commit 828863f

Browse files
committed
#2089: Find Target Indices After Sorting Array; solution & tests.
1 parent 5212749 commit 828863f

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* 2089
3+
* Find Target Indices After Sorting Array
4+
**
5+
* You are given a 0-indexed integer array nums and a target element target.
6+
* A target index is an index i such that nums[i] == target.
7+
*
8+
* Return a list of the target indices of nums
9+
* after sorting nums in non-decreasing order.
10+
* If there are no target indices, return an empty list.
11+
* The returned list must be sorted in increasing order.
12+
*
13+
* Example 1:
14+
* Input: nums = [1,2,5,2,3], target = 2
15+
* Output: [1,2]
16+
* Explanation:
17+
* After sorting, nums is [1,2,2,3,5].
18+
* The indices where nums[i] == 2 are 1 and 2.
19+
*
20+
* Example 2:
21+
* Input: nums = [1,2,5,2,3], target = 3
22+
* Output: [3]
23+
* Explanation:
24+
* After sorting, nums is [1,2,2,3,5].
25+
* The index where nums[i] == 3 is 3.
26+
*
27+
* Example 3:
28+
* Input: nums = [1,2,5,2,3], target = 5
29+
* Output: [4]
30+
* Explanation:
31+
* After sorting, nums is [1,2,2,3,5].
32+
* The index where nums[i] == 5 is 4.
33+
*
34+
* Constraints:
35+
* • 1 <= nums.length <= 100
36+
* • 1 <= nums[i], target <= 100
37+
*
38+
* Hint 1:
39+
* Try "sorting" the array first.
40+
*
41+
* Hint 2:
42+
* Now find all indices in the array whose values are equal to target.
43+
**
44+
* https://leetcode.com/problems/find-target-indices-after-sorting-array/
45+
***/
46+
47+
using System.Collections.Generic;
48+
49+
namespace Problems;
50+
51+
public class FindTargetIndicesAfterSortingArray
52+
{
53+
public IList<int> TargetIndices( int[] nums, int target )
54+
{
55+
int lessThanCount = 0;
56+
int targetCount = 0;
57+
58+
foreach ( int num in nums )
59+
{
60+
if ( num < target )
61+
{
62+
lessThanCount++;
63+
}
64+
else if ( num == target )
65+
{
66+
targetCount++;
67+
}
68+
}
69+
70+
int[] result = new int[targetCount];
71+
72+
for ( int i = 0; i < targetCount; i++ )
73+
{
74+
result[i] = lessThanCount + i;
75+
}
76+
77+
return result;
78+
}
79+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using System.Collections.Generic;
2+
3+
using NUnit.Framework;
4+
5+
using Problems;
6+
7+
public class FindTargetIndicesAfterSortingArrayTests
8+
{
9+
[TestCase( new int[] { 1, 2, 5, 2, 3 }, 2, ExpectedResult = new int[] { 1, 2 } )]
10+
[TestCase( new int[] { 1, 2, 5, 2, 3 }, 3, ExpectedResult = new int[] { 3 } )]
11+
[TestCase( new int[] { 1, 2, 5, 2, 3 }, 5, ExpectedResult = new int[] { 4 } )]
12+
public IList<int> TargetIndicesTest( int[] nums, int target ) =>
13+
new FindTargetIndicesAfterSortingArray().TargetIndices( nums, target );
14+
}

0 commit comments

Comments
 (0)