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     }
pp
原文地址:https://www.cnblogs.com/wangxiaoyong/p/8926666.html