|
| 1 | +// Source : https://leetcode.com/problems/minimum-distance-to-the-target-element/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-03 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given an integer array nums (0-indexed) and two integers target and start, find an index i such |
| 8 | + * that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x. |
| 9 | + * |
| 10 | + * Return abs(i - start). |
| 11 | + * |
| 12 | + * It is guaranteed that target exists in nums. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * Input: nums = [1,2,3,4,5], target = 5, start = 3 |
| 17 | + * Output: 1 |
| 18 | + * Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * |
| 22 | + * Input: nums = [1], target = 1, start = 0 |
| 23 | + * Output: 0 |
| 24 | + * Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 1. |
| 25 | + * |
| 26 | + * Example 3: |
| 27 | + * |
| 28 | + * Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0 |
| 29 | + * Output: 0 |
| 30 | + * Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = |
| 31 | + * 0. |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * |
| 35 | + * 1 <= nums.length <= 1000 |
| 36 | + * 1 <= nums[i] <= 10^4 |
| 37 | + * 0 <= start < nums.length |
| 38 | + * target is in nums. |
| 39 | + ******************************************************************************************************/ |
| 40 | + |
| 41 | +class Solution { |
| 42 | +public: |
| 43 | + int getMinDistance(vector<int>& nums, int target, int start) { |
| 44 | + int minDist = nums.size(); |
| 45 | + for(int i=start; i < nums.size(); i++){ |
| 46 | + if ( target == nums[i] ) { |
| 47 | + minDist = i - start; |
| 48 | + break; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + for (int i=start; i>=0; i--) { |
| 53 | + if ( target == nums[i] && start - i <= minDist) { |
| 54 | + minDist = start - i; |
| 55 | + break; |
| 56 | + } |
| 57 | + } |
| 58 | + return minDist; |
| 59 | + } |
| 60 | +}; |
0 commit comments