給一個超級大的排好序的vector [abbcccdddeeee]好比,要求返回[{1,a}, {2,b}, {3,c}, {4,d}, {5,e}......]複雜度要優於O(N)
分析:java
若是是binary search找每一個char的上下界,worst case要找n次,時間複雜度O(nlogn)spa
因此考慮每次比較start point和start point + 2^n位置上的數,假如同樣就continue,不同就在區間裏面binary search找上界,這樣worst case O(N)code
1 package fb; 2 3 import java.util.*; 4 5 public class ReorganizeVector { 6 7 public List<List<Character>> reorganize(String str) { 8 List<List<Character>> res = new ArrayList<List<Character>>(); 9 if (str==null || str.length()==0) return res; 10 int starter = 0; 11 int n = 0; 12 while (starter < str.length()) { 13 char cur = str.charAt(starter); 14 int index = starter + (int)Math.pow(2, n); 15 while (index < str.length() && str.charAt(index) == cur) { 16 n++; 17 index = starter + (int)Math.pow(2, n); 18 } 19 if (index >= str.length()) 20 index = str.length() - 1; 21 int rightEdge = findRight(str, starter, index, cur); 22 List<Character> newItem = new ArrayList<Character>(); 23 newItem.add((char)('0'+ rightEdge-starter+1)); 24 newItem.add(cur); 25 res.add(newItem); 26 27 starter = rightEdge + 1; 28 n = 0; 29 } 30 return res; 31 } 32 33 public int findRight(String str, int starter, int end, char target) { 34 int l = starter; 35 int r = end; 36 while (l <= r) { 37 int m = (l + r)/2; 38 if (str.charAt(m) == target) 39 l = m + 1; 40 else r = m - 1; 41 } 42 return r; 43 } 44 45 /** 46 * @param args 47 */ 48 public static void main(String[] args) { 49 // TODO Auto-generated method stub 50 ReorganizeVector sol = new ReorganizeVector(); 51 List<List<Character>> res = sol.reorganize("abbcccddddeeeee"); 52 for (List<Character> line : res) { 53 for (Character c : line) System.out.print(c); 54 System.out.println(""); 55 } 56 } 57 58 }