FB面经prepare: Count the number of Vector
2017-02-15 03:29
417 查看
给一个超级大的排好序的vector [abbcccdddeeee]比如,要求返回[{1,a}, {2,b}, {3,c}, {4,d}, {5,e}......]复杂度要优于O(N)
分析:
如果是binary search找每个char的上下界,worst case要找n次,时间复杂度O(nlogn)
所以考虑每次比较start point和start point + 2^n位置上的数,假如一样就continue,不一样就在区间里面binary search找上界,这样worst case O(N)
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 }
相关文章推荐
- Regex 101 Exercise I9 - Count the number of matches
- Count the number of alphabets, spaces, digits and other characters in one line character
- Count the number of possible triangles
- FB面经 Prepare: LCA of Deepest Nodes in Binary Tree
- function to count the number of "1" of one byte
- Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.
- Count the number of bits that are on in an unsigned integer(计算一个无符整数中1Bit的个数)-- (1)
- *Count the number of possible triangles
- OpenCV count the number of connected camera 检测连接的摄像头的数量
- Error Number : 1547 Error Message: Column count of mysql.proc is wrong. Expected 20, found 16. The
- R: count number of distinct values in a vector
- 三角形的数目 Count the number of possible triangles
- quick count the number of the rows in a big table
- Count the number of occurrences in a sorted array
- count the number of "1" in the binary figure
- count the number of 2s
- Write a method to count the number of 2s between 0 and n
- 在排序数组中的出现次数 Count the number of occurrences in a sorted array
- count the number of objects--物体计数
- python int to binary and count the number of 1