53
53
54
54
<!-- 这里可写通用的实现逻辑 -->
55
55
56
+ ** 方法一:一次遍历**
57
+
58
+ 遍历数组,找到所有等于 ` target ` 的下标,然后计算 ` abs(i - start) ` ,取最小值即可。
59
+
60
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 ` nums ` 的长度。
61
+
56
62
<!-- tabs:start -->
57
63
58
64
### ** Python3**
62
68
``` python
63
69
class Solution :
64
70
def getMinDistance (self , nums : List[int ], target : int , start : int ) -> int :
65
- res = inf
66
- for i, num in enumerate (nums):
67
- if num == target:
68
- res = min (res , abs (i - start))
69
- return res
71
+ ans = inf
72
+ for i, x in enumerate (nums):
73
+ if x == target:
74
+ ans = min (ans , abs (i - start))
75
+ return ans
70
76
```
71
77
72
78
### ** Java**
@@ -76,13 +82,14 @@ class Solution:
76
82
``` java
77
83
class Solution {
78
84
public int getMinDistance (int [] nums , int target , int start ) {
79
- int res = Integer . MAX_VALUE ;
80
- for (int i = 0 ; i < nums. length; ++ i) {
85
+ int n = nums. length;
86
+ int ans = n;
87
+ for (int i = 0 ; i < n; ++ i) {
81
88
if (nums[i] == target) {
82
- res = Math . min(res , Math . abs(i - start));
89
+ ans = Math . min(ans , Math . abs(i - start));
83
90
}
84
91
}
85
- return res ;
92
+ return ans ;
86
93
}
87
94
}
88
95
```
@@ -93,17 +100,39 @@ class Solution {
93
100
class Solution {
94
101
public:
95
102
int getMinDistance(vector<int >& nums, int target, int start) {
96
- int res = nums.size();
97
- for (int i = 0; i < nums.size(); ++i) {
103
+ int n = nums.size();
104
+ int ans = n;
105
+ for (int i = 0; i < n; ++i) {
98
106
if (nums[ i] == target) {
99
- res = min(res , abs(i - start));
107
+ ans = min(ans , abs(i - start));
100
108
}
101
109
}
102
- return res ;
110
+ return ans ;
103
111
}
104
112
};
105
113
```
106
114
115
+ ### **Go**
116
+
117
+ ```go
118
+ func getMinDistance(nums []int, target int, start int) int {
119
+ ans := 1 << 30
120
+ for i, x := range nums {
121
+ if t := abs(i - start); x == target && t < ans {
122
+ ans = t
123
+ }
124
+ }
125
+ return ans
126
+ }
127
+
128
+ func abs(x int) int {
129
+ if x < 0 {
130
+ return -x
131
+ }
132
+ return x
133
+ }
134
+ ```
135
+
107
136
### ** ...**
108
137
109
138
```
0 commit comments