File tree 1 file changed +63
-0
lines changed
2089-find-target-indices-after-sorting-array
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+
4
+ int firstOccurance (vector<int > &arr, int val){
5
+ int result = -1 ;
6
+ if (arr.size ()==0 ){
7
+ return result;
8
+ }
9
+ int start = 0 ;
10
+ int end = arr.size () - 1 ;
11
+ int mid;
12
+ while (start<=end){
13
+ mid = start + (end- start)/2 ;
14
+ if (arr[mid]==val){
15
+ result = mid;
16
+ end = mid - 1 ;
17
+ }
18
+ else if (arr[mid] < val){
19
+ start = mid + 1 ;
20
+ }
21
+ else {
22
+ end = mid - 1 ;
23
+ }
24
+ }
25
+ return result;
26
+ }
27
+
28
+ int lastOccurance (vector<int > &arr, int val){
29
+ int result = -1 ;
30
+ if (arr.size ()==0 ){
31
+ return result;
32
+ }
33
+ int start = 0 ;
34
+ int end = arr.size () - 1 ;
35
+ int mid;
36
+ while (start<=end){
37
+ mid = start + (end- start)/2 ;
38
+ if (arr[mid]==val){
39
+ result = mid;
40
+ start = mid + 1 ;
41
+ }
42
+ else if (arr[mid] < val){
43
+ start = mid + 1 ;
44
+ }
45
+ else {
46
+ end = mid - 1 ;
47
+ }
48
+ }
49
+ return result;
50
+ }
51
+
52
+ vector<int > targetIndices (vector<int >& nums, int target) {
53
+ sort (nums.begin (), nums.end ());
54
+ vector<int > ans;
55
+ int first_occurance = firstOccurance (nums, target);
56
+ if (first_occurance==-1 ) return ans;
57
+ int last_occurance = lastOccurance (nums, target);
58
+ for (int i=first_occurance; i<=last_occurance; i++){
59
+ ans.push_back (i);
60
+ }
61
+ return ans;
62
+ }
63
+ };
You can’t perform that action at this time.
0 commit comments