xinyu04

导航

LeetCode 1182 Shortest Distance to Target Color 二分

You are given an array colors, in which there are three colors: 1, 2 and 3.

You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.

Solution

给定一系列颜色的分布,现有若干询问,问离位置 \(i\) 最近的颜色 \(c\) 的距离。

那么我们将每个颜色的坐标存进 \(vector\) 里面,此时坐标是有序的。那么直接在需要查询的元素里面进行二分查找即可。

点击查看代码
class Solution {
private:
    vector<int> ans;
    
    int binary_check(vector<int>&rng, int idx){
        int n = rng.size();
        if(n==0)return -1;
        if(rng[0]>idx) return rng[0]-idx;
        if(rng[n-1]<idx) return idx-rng[n-1];
        auto lidx = lower_bound(rng.begin(), rng.end(), idx);// lidx>= idx
        auto ridx = upper_bound(rng.begin(), rng.end(), idx);// ridx > idx
        if(*lidx > idx && lidx>rng.begin())lidx--;
        return min(abs(*lidx-idx), abs(*ridx-idx));
        
    }
    
public:
    vector<int> shortestDistanceColor(vector<int>& colors, vector<vector<int>>& queries) {
        int n = colors.size();vector<vector<int>> range(4);
        int q = queries.size();
        for(int i=0;i<n;i++){
            range[colors[i]].push_back(i);
        }
        for(int i=0;i<q;i++){
            ans.push_back(binary_check(range[queries[i][1]], queries[i][0]));
        }
        return ans;
    }
};

posted on 2022-09-16 16:53  Blackzxy  阅读(10)  评论(0编辑  收藏  举报