【LeetCode】1182. Shortest Distance to Target Color 解题报告 (C++)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址: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:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
Output: [3,0,3]
Explanation:
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
Input: colors = [1,2], queries = [[0,3]]
Output: [-1]
Explanation: There is no 3 in the array.
Constraints:
1 <= colors.length <= 5*10^4
1 <= colors[i] <= 3
1 <= queries.length <= 5*10^4
queries[i].length == 2
0 <= queries[i][0] < colors.length
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] >= target
的j
,最接近于target的数字应该是nums[j - 1]
或者nums[j]
。故这里需要做个判断,到底是哪个数字最接近target。
举题目的例子说明:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
字典m如下:
{
{1: 0, 1, 3},
{2: 2, 5, 6},
{3: 4, 7, 8}
}
对于query = [1,3],即找出离colors[1] = 1最近的3。在m[3]中做二分查找找出最接近1的数字,找到了4,所以距离是4 - 1 = 3;
对于query = [2,2],即找出离colors[2] = 2最近的2。在m[2]中做二分查找找出最接近2的数字,找到了2,所以距离是2 - 2 = 0;
对于query = [6,1],即找出离colors[6] = 2最近的1。在m[1]中做二分查找找出最接近6的数字,找到了3,所以距离是6 - 3 = 3;
如果题目出现的是:
对于query = [5,3],即找出离colors[5] = 2最近的3。在m[3]中做二分查找找出最接近5的数字,lower_bound()找到了7(说明最接近的值是4或者7,经过判断最终选择了4),所以距离是5 - 4 = 1;
C++代码如下:
class Solution {
public:
vector<int> shortestDistanceColor(vector<int>& colors, vector<vector<int>>& queries) {
const int N = colors.size();
unordered_map<int, vector<int>> m;
for (int i = 0; i < N; ++i) {
m[colors[i]].push_back(i);
}
vector<int> res;
for (auto& query : queries) {
int cur = INT_MAX;
int target = query[0];
if (!m.count(query[1])) {
res.push_back(-1);
continue;
}
int pos = closest(m[query[1]], target);
res.push_back(abs(pos - target));
}
return res;
}
int closest(vector<int>& nums, int target) {
int pos = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
if (pos == 0) return nums[0];
if (pos == nums.size()) return nums[nums.size() - 1];
if (nums[pos] - target < target - nums[pos - 1])
return nums[pos];
return nums[pos - 1];
}
};
参考资料:
https://cloud.tencent.com/developer/ask/90642
https://www.bilibili.com/video/av31199112
日期
2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火
【LeetCode】1182. Shortest Distance to Target Color 解题报告 (C++)的更多相关文章
- LeetCode 821 Shortest Distance to a Character 解题报告
题目要求 Given a string S and a character C, return an array of integers representing the shortest dista ...
- 【LeetCode】821. Shortest Distance to a Character 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 过两遍数组 日期 题目地址:https://leet ...
- 【LeetCode】697. Degree of an Array 解题报告
[LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...
- 【LeetCode】802. Find Eventual Safe States 解题报告(Python)
[LeetCode]802. Find Eventual Safe States 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemi ...
- 【LeetCode】779. K-th Symbol in Grammar 解题报告(Python)
[LeetCode]779. K-th Symbol in Grammar 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingz ...
- 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)
[LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...
- 【LeetCode】881. Boats to Save People 解题报告(Python)
[LeetCode]881. Boats to Save People 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...
- 【LeetCode】813. Largest Sum of Averages 解题报告(Python)
[LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...
- 【LeetCode】166. Fraction to Recurring Decimal 解题报告(Python)
[LeetCode]166. Fraction to Recurring Decimal 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingz ...
随机推荐
- 《python编程从入门到实践》读书实践笔记(一)
本文是<python编程从入门到实践>读书实践笔记1~10章的内容,主要包含安装.基础类型.函数.类.文件读写及异常的内容. 1 起步 1.1 搭建环境 1.1.1 Python 版本选择 ...
- R合并数据框有重复匹配时只保留第一行
前言 合并数据框有重复匹配时通常会返回所有的匹配,如何只保留匹配的第一行呢?其实这个需求也很常见.如芯片探针ID和基因ID往往多对一,要合并ID对应矩阵和芯片表达矩阵时. 数据例子 data = da ...
- Oracle-trunc函数、round 函数、ceil函数和floor函数---处理数字函数使用
0.round函数 按照指定小数位数进行四舍五入运算. SELECT ROUND( number, [ decimal_places ] ) FROM DUAL #number : 待处理数值 de ...
- mysql-centos8下安装
参考文章 1.下载安装包 客服端与服务端 依赖包 2.linux下检查是否安装 rpm -qa | grep -i mysql 安装过会显示软件名称,没安装过就是空的 3.安装包传到虚拟机 先需要把安 ...
- RTSP, RTP, RTCP, RTMP傻傻分不清?
RTSP基于TCP传输请求和响应报文,RTP基于UDP传输流媒体数据,RTCP基于UDP传送传输质量信息(如丢包和延迟). 比如喀什一个局域网内10个人同时点播广州的同一个源,喀什和广州之间就要传10 ...
- 【转载】HBase基本数据操作详解【完整版,绝对精品】
转载自: http://blog.csdn.net/u010967382/article/details/37878701 概述 对于建表,和RDBMS类似,HBase也有namespace的概念,可 ...
- java.sql.SQLException: Cannot create com._51doit.pojo.User: com._51doit.pojo.User Query: select * from user where username = ? and password = ? Parameters: [AA, 123]
在从数据库中查询数据,并存入javabean中去时,报这个错误 原因:在建立User类去存储信息时没有创建无参构造方法,创建一个无参构造方法即可
- js正则表达式之密码强度验证
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 从面试官的角度,聊聊java面试流程
在这篇回答里,就讲以我常规的面试流程为例,说下java方面大致会问什么问题,以及如何确认候选人达到招聘要求. 先说面试前准备,可能有些面试官是拿到简历直接问,而且是在候选人自我介绍时再草草浏览简历,但 ...
- 简化版chmod
我们知道对文件访问权限的修改在Shell下可通过chmod来进行 例如 可以看到v.c文件从无权限到所有者可读可写可执行.群组和其他用户可读可执行 chmod函数原型 int chmod(const ...