后来又自己搞清楚了union find,又自己修改了一下代码 可算是通过了 classSolution{publicStringsmallestStringWithSwaps(String s, List<List<Integer>> pairs){char[] cs = s.toCharArray();intm=s.length();int[] uf =newint[m];for(inti=0; i < m; i++) { uf[i] = i;//initialize it}for(L...
rank[xRoot] += 1 } } func smallestStringWithSwaps(s string, pairs [][]int) string { // 初始化一个大小为 n 的并查集 unionFind := newUnionFind(len(s)) // 遍历每一对可互换的位置 for _, pair := range pairs { // 将这两个位置对应的集合合并 unionFind.union(pair[0], pair[1])...
【leetcode】1202. Smallest String With Swaps 题目如下: You are given a strings, and an array of pairs of indices in the stringpairswherepairs[i] = [a, b]indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the givenpairsany number of ...
Smallest String With Swaps 交换字符串中的元素(Medium)(JAVA) 题目地址: https://leetcode.com/problems/smallest-string-with-swaps/ 题目描述: You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the ...
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) { int n=s.size(); for(int i=0;i<n;i++)p.push_back(i); for(auto&items:pairs){ int a=items[0],b=items[1]; p[find(a)]=find(b); } vector<vector<char>>chr(n); ...
LeetCode 1202. Smallest String With Swaps You are givena string s,and anarray of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times....
Runtime:43 ms, faster than50.88%of Java online submissions for Smallest String With Swaps. Memory Usage:84.1 MB, less than94.39%of Java online submissions for Smallest String With Swaps.
classdsu{public:vector<int>f;dsu(int n){f.resize(n);for(int i=0;i<n;++i)f[i]=i;}intfind(int x){if(x==f[x])returnx;returnf[x]=find(f[x]);}voidmerge(int x,int y){int fx=find(x),fy=find(y);f[fx]=fy;}};classSolution{public:stringsmallestStringWithSwaps(string s,...
2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String (H-) 2454.Next-Greater-Element-IV (H-) 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum (M) monotonic stack: other usages 084.Largest-Rectangle-in-Histogram (H) 2334.Subarray-With-Elements-Greater-Than-Vary...
1202 Smallest String With Swaps Go 46.5% Medium 1203 Sort Items by Groups Respecting Dependencies 47.6% Hard 1204 Last Person to Fit in the Elevator 69.7% Medium 1205 Monthly Transactions II 45.1% Medium 1206 Design Skiplist 57.4% Hard 1207 Unique Number of Occurrences Go 71.6% Easy ...