zoukankan      html  css  js  c++  java
  • Leetcode: Summary Ranges

    Given a sorted integer array without duplicates, return the summary of its ranges.
    
    For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

     这种题就是要写的clean and tidy,好方法:

     1 public class Solution {
     2     public List<String> summaryRanges(int[] nums) {
     3         List<String> res = new ArrayList<String>();
     4         if (nums==null || nums.length==0) return res;
     5         for (int i=0; i<nums.length; i++) {
     6             int temp = nums[i];
     7             while (i+1<nums.length && nums[i+1]==nums[i]+1) i++;
     8             if (temp == nums[i]) {
     9                 res.add(temp+"");
    10             }
    11             else {
    12                 res.add(temp+"->"+nums[i]);
    13             }
    14         }
    15         return res;
    16     }
    17 }

     维护两个指针的方法:

     1 public class Solution {
     2     public List<String> summaryRanges(int[] nums) {
     3         List<String> res = new ArrayList<String>();
     4         if (nums == null || nums.length == 0) return res;
     5         int l= 0, r = 0;
     6         for (r=0; r<nums.length-1; r++) {
     7             if (nums[r] != nums[r+1]-1) {
     8                 if (nums[r] == nums[l]) res.add(nums[l] + "");
     9                 else res.add(nums[l] + "->" + nums[r]);
    10                 l = r+1;
    11             }
    12         }
    13         if (nums[r] == nums[l]) res.add(nums[l] + "");
    14         else res.add(nums[l] + "->" + nums[r]);
    15         return res;
    16     }
    17 }
  • 相关阅读:
    用nodejs 开发的智能提示
    分布式系统之消息中间件rabbitmq
    理解RESTful架构
    zf框架的思想及学习总结
    php网上支付易宝
    phpstorm使用技巧
    phpstorm使用技巧
    mysql中的数据类型
    CF113D 高斯消元、dp
    bzoj4008: [HNOI2015]亚瑟王 dp
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5059022.html
Copyright © 2011-2022 走看看