58
58
59
59
<!-- 这里可写通用的实现逻辑 -->
60
60
61
+ ** 方法一:排序**
62
+
63
+ 将数组 ` nums ` 排序后,遍历数组,找出所有等于 ` target ` 的元素的下标,将其加入结果数组中。
64
+
65
+ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 ` nums ` 的长度。
66
+
61
67
<!-- tabs:start -->
62
68
63
69
### ** Python3**
68
74
class Solution :
69
75
def targetIndices (self , nums : List[int ], target : int ) -> List[int ]:
70
76
nums.sort()
71
- return [i for i, num in enumerate (nums) if num == target]
77
+ return [i for i, v in enumerate (nums) if v == target]
72
78
```
73
79
74
80
### ** Java**
@@ -90,22 +96,6 @@ class Solution {
90
96
}
91
97
```
92
98
93
- ### ** TypeScript**
94
-
95
- ``` ts
96
- function targetIndices(nums : number [], target : number ): number [] {
97
- nums .sort ((a , b ) => a - b );
98
- let ans = [];
99
- for (let i = 0 ; i < nums .length && nums [i ] <= target ; i ++ ) {
100
- let cur = nums [i ];
101
- if (cur == target ) {
102
- ans .push (i );
103
- }
104
- }
105
- return ans ;
106
- }
107
- ```
108
-
109
99
### ** C++**
110
100
111
101
``` cpp
@@ -114,9 +104,11 @@ public:
114
104
vector<int > targetIndices(vector<int >& nums, int target) {
115
105
sort(nums.begin(), nums.end());
116
106
vector<int > ans;
117
- for (int i = 0; i < nums.size(); ++i)
118
- if (nums[ i] == target)
107
+ for (int i = 0; i < nums.size(); ++i) {
108
+ if (nums[ i] == target) {
119
109
ans.push_back(i);
110
+ }
111
+ }
120
112
return ans;
121
113
}
122
114
};
@@ -125,15 +117,29 @@ public:
125
117
### **Go**
126
118
127
119
```go
128
- func targetIndices(nums []int, target int) []int {
120
+ func targetIndices(nums []int, target int) (ans []int) {
129
121
sort.Ints(nums)
130
- var ans []int
131
- for i, num := range nums {
132
- if num == target {
122
+ for i, v := range nums {
123
+ if v == target {
133
124
ans = append(ans, i)
134
125
}
135
126
}
136
- return ans
127
+ return
128
+ }
129
+ ```
130
+
131
+ ### ** TypeScript**
132
+
133
+ ``` ts
134
+ function targetIndices(nums : number [], target : number ): number [] {
135
+ nums .sort ((a , b ) => a - b );
136
+ let ans: number [] = [];
137
+ for (let i = 0 ; i < nums .length ; ++ i ) {
138
+ if (nums [i ] == target ) {
139
+ ans .push (i );
140
+ }
141
+ }
142
+ return ans ;
137
143
}
138
144
```
139
145
0 commit comments