zoukankan      html  css  js  c++  java
  • Careercup

    2014-05-04 00:10

    题目链接

    原题:

    Write a function return an integer that satisfies the following conditions: 
    1) positive integer 
    2) no repeated digits, eg., 123 (valid), 122 (invalid) 
    3) incremental digit sequence, eg., 1234 (valid) 1243(invalid) 
    4) the returned integer MUST be the smallest one that greater than the input. eg., input=987, return=1023 
    
    function signature could be like this: 
    String nextInteger(String input)

    题目:请设计一个函数nextInteger(),以字符串形式的整数为输入,返回一个字符串形式的整数。要去这个整数:1. 是正整数 2. 任何数位的数字不能相同 3. 各个数位由高到低必须严格递增 4. 输出的数字必须是满足上述三条件并且比输入数大最小的数。其实用英语描述,一个“next”就表达这个意思了。

    解法:分析这三个条件,可以很快发现满足条件的数是很少的。各个位的数不能重复,并且还得保持升序,这样的话可以数位动态规划的思想找出所有的数,并进行排序。对于得到的所有符合条件的数组成的数组,进行upper_bound二分查找就能得到题目要求的数了。

    代码:

     1 // http://www.careercup.com/question?id=4857362737266688
     2 #include <algorithm>
     3 #include <queue>
     4 #include <sstream>
     5 #include <string>
     6 #include <vector>
     7 using namespace std;
     8 
     9 class Solution {
    10 public:
    11     Solution() {
    12         generateNumbers();
    13     };
    14     
    15     string nextInteger(string input) {
    16         int n1, n2;
    17         vector<int>::iterator it;
    18         stringstream ss;
    19         
    20         ss << input;
    21         ss >> n1;
    22         it = upper_bound(arr.begin(), arr.end(), n1);
    23         if (it == arr.end()) {
    24             n2 = n1;
    25         } else {
    26             n2 = *it;
    27         }
    28         
    29         string output = to_string(n2);
    30         
    31         return output;
    32     };
    33 private:
    34     vector<int> arr;
    35     
    36     void generateNumbers() {
    37         queue<int> q;
    38         int n, n1;
    39         int i, d;
    40         
    41         arr.push_back(0);
    42         q.push(0);
    43         while (!q.empty()) {
    44             n = q.front();
    45             q.pop();
    46             d = n % 10;
    47             for (i = d + 1; i <= 9; ++i) {
    48                 n1 = n * 10 + i;
    49                 arr.push_back(n1);
    50                 q.push(n1);
    51             }
    52         }
    53     };
    54 };
  • 相关阅读:
    〖Linux〗秒开www.stackoverflow.com,非代理方式
    〖Linux〗git push orgin master不能解析域名的解决方法
    unity, terrain道出为obj
    unity, 顶点对齐
    world machine, 输出lightmap
    unity, scene视图查看场景时应调成正交模式
    unity, 由scriptableObject创建.asset
    unity, 播放循环背景音乐注意事项
    用audacity制作循环背景音乐
    unity, 保存prefab时material丢失问题
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3705913.html
Copyright © 2011-2022 走看看