CodeSignal 刷題 —— almostIncreasingSequence

來源:互聯網
上載者:User

標籤: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     else14         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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.