📣 独立日限时特惠: VIP通行证立减$68
123
返回列表 发新帖
楼主: jaly50
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] Leetcode个人刷题思路和自我督促贴

🔗
 楼主| jaly50 2014-12-28 13:06:07 | 只看该作者
全局:
  1. import java.util.HashMap;
  2. import java.util.Map;

  3. /*
  4. * LeetCode 155 Minimum Window Substring
  5. * Given a string S and a string T,
  6. * find the minimum window in S which will contain all the characters in T in complexity O(n).
  7. * @author: Scarlett Chen
  8. * @date: 12/27/2014 Sat 8:36 PM
  9. * Time: o(2n)
  10. * space: o(n)
  11. * 思路:记录minWindow的开始点sb,每次匹配完T的值后,删掉第一个点,继续往后找,直到T再次匹配完全。
  12. * 每次完全匹配时,更新minWindown是否有更小。
  13. */
  14. public class MinWindow {
  15.         public static String minWindow(String S, String T) {
  16.                Map<Character,Integer> map = new HashMap<Character, Integer>();
  17.                String minWindow = S;
  18.                if (T.length()> S.length()) return "";
  19.                if (T.equals(S)) return minWindow;
  20.                int count  = T.length();
  21.                for (int i=0; i<count; i++) {
  22.                    char ch = T.charAt(i);
  23.                    if (map.containsKey(ch)) {
  24.                        map.put(ch, map.get(ch)-1);
  25.                    }
  26.                    else map.put(ch, -1);
  27.                }
  28.                int sb = -1;
  29.                boolean ansExist = false;
  30.                for (int i=0; i<S.length(); i++ ) {
  31.                    char ch = S.charAt(i);
  32.                    if (map.containsKey(ch)) {
  33.                            System.out.println(ch);
  34.                            //First beginning of the window
  35.                        if (sb==-1) sb = i;
  36.                        map.put(ch, map.get(ch)+1);
  37.                        if (map.get(ch)<=0)
  38.                                count--;
  39.                        while (count==0) {
  40.                                ansExist = true;
  41.                            minWindow =i-sb+1 <minWindow.length() ? S.substring(sb,i+1): minWindow;
  42.                            ch = S.charAt(sb);
  43.                           // if (map.containsKey(ch))  must contain, since sb is the begining of the minwindow
  44.                                    map.put(ch, map.get(ch)-1);
  45.                            if (map.get(ch)<0) count++;
  46.                         sb++;
  47.                         while (sb <= S.length()-T.length() && !map.containsKey(S.charAt(sb)))
  48.                                   sb++;
  49.                         if (sb>S.length()-T.length()) return minWindow;
  50.                            }
  51.                          
  52.                            
  53.                        }
  54.                    }
  55.                   
  56.                    
  57.                
  58.               return ansExist? minWindow: "";   
  59.             }
  60.         public static void main(String[] args) {
  61.                 System.out.println(minWindow("bdab","ab"));
  62.    
  63.         }

  64. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-28 16:06:44 | 只看该作者
全局:
  1. import java.util.Stack;

  2. /*
  3. * @Author: Scarlett Chen
  4. * @date: 12/27/2014 Sat 11:42 PM
  5. * LeetCode 156  Largest Rectangle in Histogram
  6. * 1. o(n^2) + 剪枝可过
  7. * 2. 线段树,维护线段之中的最小值 +  分治 recursive 可过 http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
  8. * 3. 用栈 保持递增序列
  9. * 这个讲得特别好:http://blog.csdn.net/doc_sgl/article/details/11805519
  10. */
  11. public class LargestRectangleArea {
  12.         public int largestRectangleArea(int[] height) {
  13.         Stack<Integer> stack = new Stack<Integer>();
  14.         int n = height.length;
  15.         if (n<1) return 0;
  16.         int largest = height[0];
  17.         for (int i=0; i<=n; i++) {
  18.                 int curHeight = i==n? 0: height[i];
  19.             while (!stack.isEmpty() && height[stack.peek()] > curHeight) {
  20.                 int index = stack.pop();
  21.                 /*
  22.                  * 拿 0 3 2 5 举例
  23.                  * 之所以要i-stack.peek()-1
  24.                  * 是因为在入栈时,2<3,所以3被踢掉了。但在算2为高度的最大面积时
  25.                  * 就要算从栈内的 0 后面一位直到i:这距离就是 i-stack.peek()【就是0 +1
  26.                  */
  27.                 int curArea = height[index] * (stack.isEmpty()? i:i-stack.peek()-1);
  28.                 largest = Math.max(largest, curArea);
  29.             }
  30.              stack.push(i);
  31.             }
  32.         return largest;
  33.         }
  34.         

  35.         public static void main(String[] args) {
  36.                 // TODO Auto-generated method stub

  37.         }

  38. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-28 16:47:14 | 只看该作者
全局:
  1. import java.util.Stack;
  2. /*
  3. * LeetCode 157 Maximal Rectangle
  4. * @Author: Scarlett Chen
  5. * @date: 12/28/2014 Sun 12:44 AM
  6. * o(n*m) 有些想法自己怎么就是想不到呢~
  7. * 就是largestRectangle的多层版!!对每一行都进行栈的维护,作为底边,找最大rectangle!
  8. */

  9. public class MaxRectangle {
  10.     public static int maximalRectangle(char[][] matrix) {
  11.         int n = matrix.length;
  12.         if (n <1) return 0;
  13.         int m = matrix[0].length;
  14.         //+1 is the fake final one
  15.         // to maintain the height of each col when their base is the current row
  16.         int[] height = new int[m+1];
  17.         height[m] =0 ; // the fake one for the stack maintainance
  18.         Stack<Integer> stack = new Stack<Integer>();
  19.         int h,row,largest=0,curArea=0;
  20.         for (int i=0; i<n; i++) {
  21.            for (int j=0; j<m; j++) {
  22.                //Set the height attributes
  23.                h = 0;
  24.                row = i;
  25.                while (row>=0 &&matrix[row][j]=='1') {
  26.                    row--;
  27.                    h++;
  28.                }
  29.                height[j] = h;
  30.            }
  31.            for (int j=0; j<=m; j++) {
  32.                //Get the maximum rectangle area by stack
  33.               while (!stack.isEmpty() && height[stack.peek()] > height[j]) {
  34.                   h = stack.pop();
  35.                   curArea = height[h] * (stack.isEmpty()? j: j-stack.peek()-1);
  36.                   largest = Math.max(curArea, largest);
  37.                   
  38.               }
  39.               stack.push(j);
  40.            }
  41.            stack.removeAllElements();
  42.            }
  43.          
  44.   
  45.       return largest;  
  46.     }
  47.         public static void main(String[] args) {
  48.                 // TODO Auto-generated method stub
  49. System.out.println(maximalRectangle(new char[][] {{'1'}} ));
  50.         }

  51. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-29 02:21:52 | 只看该作者
全局:
  1. /*
  2. * Leetcode 158
  3. * @author: Scarlett Chen
  4. * @date: 12/28/2014 Sun 10:19 AM
  5. * Time(n)  easy
  6. * 一开始的想法就是 换进制,换成26进制数嘛。
  7. * 但是需要注意的是,这里的数从1-26.和之前从0-n-1是不一样的~ 所以我们手动把数转成n-1
  8. */
  9. public class ConvertToTitle {
  10.         public static String convertToTitle(int n) {
  11.         StringBuffer s = new StringBuffer();
  12.         char[] tablet = new char[26];
  13.         for (int i=0; i<tablet.length; i++)
  14.           tablet[i]=(char) ('A'+i);
  15.         int carry=0;
  16.         while (n>0) {
  17.             carry = (n-1) % 26;
  18.             n = (n-1)/ 26;
  19.             s.insert(0,tablet[carry]);
  20.         }
  21.       return s.toString();   
  22.     }
  23.         public static void main(String args[]) {
  24.                 System.out.println(convertToTitle(1));
  25.         }
  26. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-29 06:42:48 | 只看该作者
全局:
  1. import java.util.Arrays;

  2. /*
  3. * LeetCode 161  Maximum Gap
  4. * @author: Scarlett chen
  5. * @date: 12/28/2014 Sun 2:40
  6. * 找到(max-min)/(n-1) 根据平均差装箱
  7. */
  8. public class MaximumGap {
  9.     public static int maximumGap(int[] num) {
  10.     //Get the average distance between two successive elements
  11.     int n = num.length;
  12.     if (n<2) return 0;
  13.     int max= num[0], min = num[0];
  14.     // get Max and min in the array
  15.      for (int i:num) {
  16.          max = i>max? i:max;
  17.          min = i<min? i:min;
  18.      }   
  19.      //必须是ceil,否则 min*aveDis(n-1)会小于最大值的~后面就会溢出
  20.      int aveDis =(int)(Math.ceil((double)(max-min)/(n-1)));
  21.      if (aveDis==0) return 0; // all numbers are same value
  22.      // put elements into array based on the average distance
  23.      int[] maxA= new int[n+1], minA = new int[n+1];
  24.      Arrays.fill(maxA, -1);
  25.      Arrays.fill(minA, -1);
  26.      int index = 0;
  27.      for (int e:num) {
  28.         index = (e-min)/aveDis;
  29.         if (maxA[index]==-1)
  30.                 maxA[index] = e;
  31.         else maxA[index] = e>maxA[index]? e: maxA[index];
  32.         if (minA[index]==-1)
  33.                 minA[index] = e;
  34.         else minA[index] = e< minA[index]? e: minA[index];
  35.      }
  36.      int gap = 0;
  37.      int gapLeft=min, gapRight=0;// left would be maxA[i-1], right is minA[i]
  38.      for (int i=0; i<= n; i++) {
  39.              if (minA[i]!=-1)
  40.                      gapRight = minA[i];
  41.              gap = Math.max(gap, gapRight-gapLeft);
  42.              if (maxA[i]!=-1)
  43.                       gapLeft = maxA[i];
  44.            
  45.      }
  46.      return gap;
  47.     }
  48.         public static void main(String[] args) {
  49.                 // TODO Auto-generated method stub
  50.       System.out.println(maximumGap(new int[]{}));
  51.         }

  52. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-29 12:30:00 | 只看该作者
全局:
  1. import java.util.HashMap;
  2. import java.util.HashSet;
  3. import java.util.Map;
  4. /*
  5. * LeetCode 163 Fraction to Recurring Decimal
  6. * @author : Scarlett chen
  7. * @date: 12/28/2014 Sun 8:10 PM
  8. * 需要注意的地方:符号, 整数部分为零的时候符号
  9. * 极值情况 如 -2147483648 的余数,商 都有可能超过整数范围
  10. * 【最后一道leetCode  好激动!任务圆满完成!
  11. */


  12. public class FractionToDecimal {
  13.     public static String fractionToDecimal(int numerator, int denominator) {
  14.             long remainder, num;
  15.             // the long is for :fractionToDecimal(-2147483648,-1)
  16.             long intPart = (long)numerator/ denominator;
  17.             remainder = numerator % denominator;
  18.             if (remainder ==0) return String.valueOf(intPart);
  19.             //if the ans is not zero, the sign has already been given.
  20.             StringBuffer ans = new StringBuffer(String.valueOf(intPart));
  21.             ans.append('.');
  22.            
  23.             long fractionPart = 0;
  24.            
  25.             //consider the zero situation
  26.             if (Math.signum(remainder)*Math.signum(denominator) <0 && intPart==0) ans.insert(0, "-");
  27.             remainder = Math.abs(remainder);
  28.             //the long is for  fractionToDecimal(-1,-2147483648)
  29.             long den = Math.abs((long)denominator);
  30.              Map<Long,Integer> map = new HashMap<Long,Integer>();
  31.             while (remainder!=0) {
  32.                     map.put(remainder,ans.length());
  33.                     num = remainder * 10;
  34.                     fractionPart = num / den;
  35.                     remainder = num % den;
  36.                     ans.append(fractionPart);
  37.                     if (map.containsKey(remainder)) {
  38.                             ans.append(')');
  39.                             ans.insert(map.get(remainder), "(");
  40.                             return ans.toString();
  41.                     }
  42.                    
  43.             }
  44.         return ans.toString();
  45.         
  46.     }
  47.         public static void main(String[] args) {
  48.                 // TODO Auto-generated method stub
  49.        System.out.println(fractionToDecimal(-2147483648,-1));
  50.         }

  51. }
复制代码
回复

使用道具 举报

🔗
mnmunknown 2014-12-31 02:05:13 | 只看该作者
全局:
也在刷leetcode,和楼主共勉
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表