码迷,mamicode.com
首页 > 其他好文 > 详细

CodeSignal 刷题 —— almostIncreasingSequence

时间:2018-10-07 14:41:32      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:ISE   color   div   tin   pre   des   his   alt   ble   

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example

  • For sequence = [1, 3, 2, 1], the output should be
    almostIncreasingSequence(sequence) = false.

    There is no one element in this array that can be removed in order to get a strictly increasing sequence.

  • For sequence = [1, 3, 2], the output should be
    almostIncreasingSequence(sequence) = true.

    You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

Input/Output

    • [execution time limit] 0.5 seconds (cpp)

    • [input] array.integer sequence

      Guaranteed constraints:
      2 ≤ sequence.length ≤ 105,
      -105 ≤ sequence[i] ≤ 105.

    • [output] boolean

      • Return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.

 

C++解法:

 1 bool isSequence(vector<int> sequence)
 2 {
 3     set<int>iset;
 4     for(auto e: sequence)
 5         iset.insert(e);
 6     if(iset.size() != sequence.size())     //如果sequence中有重复元素,返回false
 7         return false;
 8 
 9     vector<int>v = sequence;               //如果sequence与排序后的v相等,则说明sequence是递增有序的
10     sort(v.begin(), v.end());
11     if(sequence == v)
12         return true;
13     else
14         return false;
15 
16 }
17 
18 bool almostIncreasingSequence(std::vector<int> sequence) 
19 {
20     if (isSequence(sequence))
21         return true;
22     int i = 0;
23     while (i < sequence.size())
24     {
25         vector<int> v = sequence;
26         v.erase(v.begin() + i);
27         if(isSequence(v))
28             return true;
29         ++i;
30     }
31     return false;
32 }

 

CodeSignal 刷题 —— almostIncreasingSequence

标签:ISE   color   div   tin   pre   des   his   alt   ble   

原文地址:https://www.cnblogs.com/FengZeng666/p/9749953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!