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;
        }
  • 相关阅读:
    BSGS模板(互质与不互质) 洛谷P4195、P3846
    整除分块(数论分块)
    洛谷P3327 [SDOI2015]约数个数和——莫比乌斯反演
    模块二
    模块
    二分法 匿名函数
    3.26作业
    函数的递归调用
    yield表达式 三元表达式
    3.25作业
  • 原文地址:https://www.cnblogs.com/skillking/p/9925417.html
Copyright © 2011-2022 走看看