Skip to content

Commit f00edaf

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 13.3 MB (16.70%)
1 parent 78422ca commit f00edaf

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>Given an integer array <code>nums</code> <strong>(0-indexed)</strong> and two integers <code>target</code> and <code>start</code>, find an index <code>i</code> such that <code>nums[i] == target</code> and <code>abs(i - start)</code> is <strong>minimized</strong>. Note that&nbsp;<code>abs(x)</code>&nbsp;is the absolute value of <code>x</code>.</p>
2+
3+
<p>Return <code>abs(i - start)</code>.</p>
4+
5+
<p>It is <strong>guaranteed</strong> that <code>target</code> exists in <code>nums</code>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [1,2,3,4,5], target = 5, start = 3
12+
<strong>Output:</strong> 1
13+
<strong>Explanation:</strong> nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [1], target = 1, start = 0
20+
<strong>Output:</strong> 0
21+
<strong>Explanation:</strong> nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
22+
</pre>
23+
24+
<p><strong class="example">Example 3:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
28+
<strong>Output:</strong> 0
29+
<strong>Explanation:</strong> Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
37+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
38+
<li><code>0 &lt;= start &lt; nums.length</code></li>
39+
<li><code>target</code> is in <code>nums</code>.</li>
40+
</ul>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution {
2+
public:
3+
int getMinDistance(vector<int>& nums, int target, int start) {
4+
int ans = 1e9;
5+
int n = nums.size();
6+
for (int i=0; i<n; i++) {
7+
if (nums[i] == target) ans = min(ans, abs(i - start));
8+
}
9+
return ans;
10+
}
11+
};

0 commit comments

Comments
 (0)