zoukankan      html  css  js  c++  java
  • FB面经prepare: Count the number of Vector

    给一个超级大的排好序的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 }
  • 相关阅读:
    orm 对象关系映射 指 表与类之间的映射 # 40
    事务 视图 触发器 函数 (内置) 存储过程 流程控制 索引 # 39
    exist 存在 Python操作mysql pymysql sql注入问题 # 38
    基本查询语句与方法 多表查询 # 37
    外键 #36
    存储引擎 索引 数据类型 约束条件 # 35
    mysql安装 登录 修改密码 库,表,记录(增删改查) # 34
    进程池和线程池 协程 # 33
    GIL全局解释器锁
    # 并发编程 -进程理论-进程的方法
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6399857.html
Copyright © 2011-2022 走看看