zoukankan      html  css  js  c++  java
  • 1291. Sequential Digits (M)

    Sequential Digits (M)

    题目

    An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

    Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

    Example 1:

    Input: low = 100, high = 300
    Output: [123,234]
    

    Example 2:

    Input: low = 1000, high = 13000
    Output: [1234,2345,3456,4567,5678,6789,12345]
    

    Constraints:

    • 10 <= low <= high <= 10^9

    题意

    在给定范围内找到所有整数,是这些整数满足每一位上的数字都比前一位的数字大1。

    思路

    所有这样的数字一共才不到一百个,直接遍历所有这样的整数,判断是否在指定范围里。


    代码实现

    Java

    排序

    class Solution {
        public List<Integer> sequentialDigits(int low, int high) {
            List<Integer> list = new ArrayList<>();
            int first = 1, num = 1;
            while (first <= 8) {
                if (num >= low && num <= high) {
                    list.add(num);
                }
                if (num > high || num % 10 == 9) {
                    num = ++first;
                    continue;
                }
                num = num * 10 + num % 10 + 1;
            }
            Collections.sort(list);
            return list;
        }
    }
    

    不排序

    class Solution {
        public List<Integer> sequentialDigits(int low, int high) {
            List<Integer> list = new ArrayList<>();
            Queue<Integer> q = new LinkedList<>();
            for (int i = 1; i < 9; i++) {
                q.offer(i);
            }
            while (!q.isEmpty()) {
                int num = q.poll();
                if (num >= low && num <= high) {
                    list.add(num);
                }
                if (num <= high && num % 10 < 9) {
                    q.offer(num * 10 + num % 10 + 1);
                }
            }
            return list;
        }
    }
    
  • 相关阅读:
    mr程序无法输出日志进行调试的解决方法
    2015年度总结
    Hadoop数据目录迁移
    Oracle数据迁移至HBase操作记录
    Hadoop端口一览表
    Hadoop Maven pom文件示例
    十个书写Node.js REST API的最佳实践(下)
    iOS 程序从开发完到上 AppStore 那点事儿
    拿什么拯救你,我的三十五岁
    Spark 以及 spark streaming 核心原理及实践
  • 原文地址:https://www.cnblogs.com/mapoos/p/13697895.html
Copyright © 2011-2022 走看看