leetCode题解之字符最短路径解法2

1、题目描述

2、分析

  之前使用的大循环再向两边寻找的算法是 O(n^2)复杂度的,可以利用 multimap降低其复杂度。

3、代码

 1 vector<int> shortestToChar(string S, char C) {
 2         // 使用标准库中的multimap 存储每个字符和其下标
 3         // multimap的优势在于key值可以重复
 4         vector<int> ans;
 5         multimap<char,int> m;
 6         for( int i = 0; i< S.size(); i++)
 7             m.insert( make_pair(S[i],i) );
 8         
 9         for( int i =0;i<S.size();i++)
10         {
11             if( S[i] == C )
12             {
13                 ans.push_back(0);
14             }    
15             else
16             {
17                 int k = S.size()-1;
18                 for( auto pos = m.lower_bound( C ); pos != m.upper_bound( C ); pos++ )
19                 {
20                     
21                         if( abs( pos->second - i ) < k )
22                             k = abs( pos->second -i );
23                 }
24                  ans.push_back(k); 
25             } 
26         }
27         return ans; 
28     }

 

转载于:https://www.cnblogs.com/wangxiaoyong/p/8926666.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值