题目地址:https://leetcode-cn.com/problems/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.

Example 1:

  1. Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
  2. Output: [3,0,3]
  3. Explanation:
  4. The nearest 3 from index 1 is at index 4 (3 steps away).
  5. The nearest 2 from index 2 is at index 2 itself (0 steps away).
  6. The nearest 1 from index 6 is at index 3 (3 steps away).

Example 2:

  1. Input: colors = [1,2], queries = [[0,3]]
  2. Output: [-1]
  3. Explanation: There is no 3 in the array.

Constraints:

  1. 1 <= colors.length <= 5*10^4
  2. 1 <= colors[i] <= 3
  3. 1 <= queries.length <= 5*10^4
  4. queries[i].length == 2
  5. 0 <= queries[i][0] < colors.length
  6. 1 <= queries[i][1] <= 3

题目大意

给你一个数组 colors,里面有 1、2、 3 三种颜色。
我们需要在 colors 上进行一些查询操作 queries,其中每个待查项都由两个整数 i 和 c 组成。
现在请你帮忙设计一个算法,查找从索引 i 到具有目标颜色 c 的元素之间的最短距离。
如果不存在解决方案,请返回 -1。

解题方法

字典+二分查找

这个题让我们找到和nums[i]最接近的target = c的位置。看了下数据规模,O(N^2)的方法就放弃吧,这个题的最大时间复杂度限制在了O(N*log(N))

本题困难的地方在于,我们如何快速的找到距离i最近的c的位置?一个直观的想法当然是找出所有的c的位置,然后从中找出和i位置最接近的那个。为了保存每个数字的所有出现过的位置,当然使用字典比较好,字典的格式是unordered_map<int, vector<int>>,即键是数字,值是一个有序的列表表示了该数字所有的出现过的位置。所以,问题抽象成了:如何在一个有序的列表中,找出最接近的target的数字?

想到时间复杂度的限制,很明显的思路就来了:使用二分查找,找到最接近的target。可以使用lower_bound()找出num[j] >= targetj,最接近于target的数字应该是nums[j - 1]或者nums[j]。故这里需要做个判断,到底是哪个数字最接近target。

举题目的例子说明:

  1. Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
  2. 字典m如下:
  3. {
  4. {1: 0, 1, 3},
  5. {2: 2, 5, 6},
  6. {3: 4, 7, 8}
  7. }
  8. 对于query = [1,3],即找出离colors[1] = 1最近的3。在m[3]中做二分查找找出最接近1的数字,找到了4,所以距离是4 - 1 = 3
  9. 对于query = [2,2],即找出离colors[2] = 2最近的2。在m[2]中做二分查找找出最接近2的数字,找到了2,所以距离是2 - 2 = 0
  10. 对于query = [6,1],即找出离colors[6] = 2最近的1。在m[1]中做二分查找找出最接近6的数字,找到了3,所以距离是6 - 3 = 3

如果题目出现的是:

  1. 对于query = [5,3],即找出离colors[5] = 2最近的3。在m[3]中做二分查找找出最接近5的数字,lower_bound()找到了7(说明最接近的值是4或者7,经过判断最终选择了4),所以距离是5 - 4 = 1

C++代码如下:

  1. class Solution {
  2. public:
  3. vector<int> shortestDistanceColor(vector<int>& colors, vector<vector<int>>& queries) {
  4. const int N = colors.size();
  5. unordered_map<int, vector<int>> m;
  6. for (int i = 0; i < N; ++i) {
  7. m[colors[i]].push_back(i);
  8. }
  9. vector<int> res;
  10. for (auto& query : queries) {
  11. int cur = INT_MAX;
  12. int target = query[0];
  13. if (!m.count(query[1])) {
  14. res.push_back(-1);
  15. continue;
  16. }
  17. int pos = closest(m[query[1]], target);
  18. res.push_back(abs(pos - target));
  19. }
  20. return res;
  21. }
  22. int closest(vector<int>& nums, int target) {
  23. int pos = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
  24. if (pos == 0) return nums[0];
  25. if (pos == nums.size()) return nums[nums.size() - 1];
  26. if (nums[pos] - target < target - nums[pos - 1])
  27. return nums[pos];
  28. return nums[pos - 1];
  29. }
  30. };

参考资料:
https://cloud.tencent.com/developer/ask/90642
https://www.bilibili.com/video/av31199112

日期

2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火

【LeetCode】1182. Shortest Distance to Target Color 解题报告 (C++)的更多相关文章

  1. LeetCode 821 Shortest Distance to a Character 解题报告

    题目要求 Given a string S and a character C, return an array of integers representing the shortest dista ...

  2. 【LeetCode】821. Shortest Distance to a Character 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 过两遍数组 日期 题目地址:https://leet ...

  3. 【LeetCode】697. Degree of an Array 解题报告

    [LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...

  4. 【LeetCode】802. Find Eventual Safe States 解题报告(Python)

    [LeetCode]802. Find Eventual Safe States 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemi ...

  5. 【LeetCode】779. K-th Symbol in Grammar 解题报告(Python)

    [LeetCode]779. K-th Symbol in Grammar 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingz ...

  6. 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

    [LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  7. 【LeetCode】881. Boats to Save People 解题报告(Python)

    [LeetCode]881. Boats to Save People 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  8. 【LeetCode】813. Largest Sum of Averages 解题报告(Python)

    [LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...

  9. 【LeetCode】166. Fraction to Recurring Decimal 解题报告(Python)

    [LeetCode]166. Fraction to Recurring Decimal 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingz ...

随机推荐

  1. pycurl报错: ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend

    报错: ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl ...

  2. R语言实战(第二版)-part 1笔记

    说明: 1.本笔记对<R语言实战>一书有选择性的进行记录,仅用于个人的查漏补缺 2.将完全掌握的以及无实战需求的知识点略去 3.代码直接在Rsudio中运行学习 R语言实战(第二版) pa ...

  3. R之dplyr::select/mutate函数扩展

    select函数 dplyr包select函数用的很多,不过我们一般也是通过正反选列名或数字来选择列. 常见用法如: select(iris,c(1,3)) select(iris,1,3) #同上 ...

  4. R绘图布局包 customLayout

    今天介绍一个R画图布局的包,地址如下: https://github.com/zzawadz/customLayout https://www.customlayout.zstat.pl/index. ...

  5. ProxyApi-大数据采集用的IP代理池

    用于大数据采集用的代理池 在数据采集的过程中,最需要的就是一直变化的代理ip. 自建adsl为问题是只有一个区域的IP. 买的代理存在的问题是不稳定,影响采集效率. 云vps不允许安装花生壳等,即使有 ...

  6. 【模板】一般图最大匹配(带花树算法)/洛谷P6113

    题目链接 https://www.luogu.com.cn/problem/P6113 题目大意 给定一个 \(n\) 个点 \(m\) 条边的无向图,求该图的最大匹配. 题目解析 二分图最大匹配,一 ...

  7. 【模板】最小费用最大流(网络流)/洛谷P3381

    题目链接 https://www.luogu.com.cn/problem/P3381 题目大意 输入格式 第一行包含四个正整数 \(n,m,s,t\),分别表示点的个数.有向边的个数.源点序号.汇点 ...

  8. 学习java的第六天

    一.今日收获 1.开始了学习手册第二章的学习 2.了解了java里的常量与变量以及数据类型,与c语言的内容类似 二.今日难题 1.都是基础知识,没有什么难题 三.明日目标 1.继续学习java学习手册 ...

  9. 【Reverse】每日必逆0x02

    BUU SimpleRev 附件 https://files.buuoj.cn/files/7458c5c0ce999ac491df13cf7a7ed9f1/SimpleRev 题解 查壳 拖入iad ...

  10. Prompt branches and tab completion

    $ chmod +x ~/.git-prompt.sh $ chmod +x ~/.git-completion.bash $ atom ~/.bash_profile 编辑.bash_profile ...