Codility上的練習 (14),codility上練習14

來源:互聯網
上載者:User

Codility上的練習 (14),codility上練習14

(1) TieRopes

給定n段繩子——一個正整數數組,和一個正整數K,每次只能串連相鄰的兩根繩子,串連好了繩子長度為之前的繩子長度和,並且位置不變,問這麼串連下去,最多能形成多少根長度至少為K的繩子?

資料範圍: N[1..10^5], 數組元素和K的範圍[1..10^9]。


要求複雜度: 時間O(N), 空間O(1)。


分析: 假設最終扔掉一根繩子,那麼為什麼不把這根繩子串連到它相鄰的繩子上呢? 所以不會扔繩子的…… 於是就線性掃一下 總和 >= K就是一條。。。

// you can also use includes, for example:// #include <algorithm>int solution(int K, vector<int> &A) {    // write your code in C++11    int r = 0;    for (int i = 0; i < A.size();) {        int length = 0;        for (; (i < A.size()) && (length < K); length += A[i++])        ;        if (length >= K) {            ++r;        }    }    return r;    }


(2) MaxNonoverlappingSegments

給定N條線段,每條線段是[A[i],B[i]]的形式(閉區間),線段已經按照結束端點排序了,求最多能選出多少條沒有公用點的線段。

資料範圍 N [0..30000], A, B數組都是整數,範圍[0..10^9]。

要求複雜度: 時間空間都是O(1)。


分析: 這個就是活動安排問題……而且區間都按右端點排序了,貪心一個一個取,相交就扔掉就可以了。


代碼:

// you can use includes, for example:// #include <algorithm>// you can write to stdout for debugging purposes, e.g.// cout << "this is a debug message" << endl;int solution(vector<int> &A, vector<int> &B) {    // write your code in C++11    int last = -1, answer = 0;    for (int i = 0; i < A.size(); ++i) {        if ((last < 0) || (A[i] > B[last])) {            last = i;            ++answer;        }    }    return answer;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.