zoukankan      html  css  js  c++  java
  • 228. Summary Ranges

    一、题目

      1、审题

      

      2、分析

        给出一个有序的无重复的整形数组,返回一个描述数组‘概要’的字符串 List。

    二、解答

      1、思路

        方法一、

          采用两个指针记录前后的元素是否连续。

      

        public List<String> summaryRanges(int[] nums) {
        
            int len;
            List<String> list = new ArrayList<String>();
            if(nums == null || (len = nums.length) == 0)
                return list;
    
            int cur = 0, pre = 0;
            for (int i = 1; i < len; i++) {
                if(nums[i] == nums[i - 1] + 1) {
                    cur = i;
                }
                else {
                    if(cur == pre)
                        list.add(nums[pre] + "");
                    else 
                        list.add(nums[pre] + "->" + nums[cur]);
                    cur = pre = i;
                }
            }
            // the last one
            if(cur == pre)
                list.add(nums[pre] + "");
            else 
                list.add(nums[pre] + "->" + nums[cur]);
            return list;
        }

      方法二、

        直接以当前元素为每一个组合的起始,求出每一个组合。

      public List<String> summaryRanges(int[] nums) {
            int len;
            List<String> list = new ArrayList<String>();
            if(nums == null || (len = nums.length) == 0)
                return list;
            
            for (int i = 0; i < len; i++) {
                int a = nums[i];
                while(i + 1 < len && nums[i + 1] - nums[i] == 1)
                    i++;
                if(a != nums[i])
                    list.add(a + "->" + nums[i]);
                else
                    list.add(a + "");
            }
            return list;
        }
  • 相关阅读:
    字符串----不可重叠的最长重复子串
    字符串----最长重复子串
    字符串----HDU-1358
    字符串----hiho字符串(尺取法)
    字符串匹配(二)----KMP算法
    字符串匹配(一)----Rabin-Karp算法
    字符串----最短摘要生成(尺取法)
    【Hibernate 检索策略】
    【Hibernate 多表查询】
    【Hibernate QBC】
  • 原文地址:https://www.cnblogs.com/skillking/p/9925417.html
Copyright © 2011-2022 走看看