Featured image of post Minimum Distance to the Target Element

Minimum Distance to the Target Element

1848. Minimum Distance to the Target Element

Algorithm Steps

  1. Iterate nums and store the indices of all elements that satisfy nums[i] == target in pos
  2. Iterate pos, calculate the minimum abs(i - start)

Complexity Analysis

Time complexity: O(n)

Space complexity: O(n)

C++ Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    int getMinDistance(vector<int>& nums, int target, int start) {
        std::vector<int> pos;

        // record all indices that satisfy nums[i] == target
        for (int i = 0; i < nums.size(); i ++ )
            if (nums[i] == target)
                pos.push_back(i);

        int res = INT_MAX;

        // find minimum distance
        for (int x: pos)
            res = std::min(res, std::abs(x - start));

        return res;
    }
};

Python Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
        pos = []
        for i, x in enumerate(nums):
            if x == target:
                pos.append(i)

        res = float('inf')
        for x in pos:
            res = min(res, abs(x - start))

        return res

Go Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
func getMinDistance(nums []int, target int, start int) int {
    pos := []int{}
    for i, x := range nums {
        if x == target {
            pos = append(pos, i)
        }
    }

    res := math.MaxInt
    for _, x := range pos {
        t := x - start
        if t < 0 {
            t = -t
        }
        res = min(res, t)
    }

    return res
}

JavaScript Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * @param {number[]} nums
 * @param {number} target
 * @param {number} start
 * @return {number}
 */
var getMinDistance = function (nums, target, start) {
  let pos = [];
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === target) {
      pos.push(i);
    }
  }

  let res = Infinity;
  for (let x of pos) {
    res = Math.min(res, Math.abs(x - start));
  }

  return res;
};
Built with Hugo
Theme Stack designed by Jimmy