[codility]CountDistinctSlices

来源:互联网 发布:我的世界编程代码 编辑:程序博客网 时间:2024/06/14 01:04
Task description

An integer M and a non-empty zero-indexed array A consisting of N non-negative integers are given. All integers in array A are less than or equal to M.

A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The slice consists of the elements A[P], A[P + 1], ..., A[Q]. A distinct slice is a slice consisting of only unique numbers. That is, no individual number occurs more than once in the slice.

For example, consider integer M = 6 and array A such that:

    A[0] = 3    A[1] = 4    A[2] = 5    A[3] = 5    A[4] = 2

There are exactly nine distinct slices: (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2), (3, 3), (3, 4) and (4, 4).

The goal is to calculate the number of distinct slices.

Write a function:

int solution(int M, vector<int> &A);

that, given an integer M and a non-empty zero-indexed array A consisting of N integers, returns the number of distinct slices.

If the number of distinct slices is greater than 1,000,000,000, the function should return 1,000,000,000.

For example, given integer M = 6 and array A such that:

    A[0] = 3    A[1] = 4    A[2] = 5    A[3] = 5    A[4] = 2

the function should return 9, as explained above.

Assume that:

  • N is an integer within the range [1..100,000];
  • M is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [0..M].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

// 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(int M, vector<int> &A) {    // write your code in C++11    int left = 0;    int right = 0;    int size = A.size();    vector<bool> visited(M+1, false);    const int kDistinctSlices = 1000000000;    long long ret = 0;    for (;right < size; right++) {        if(!visited[A[right]]) {            visited[A[right]] = true;            continue;        }        int tmp_left = left;        while (A[left] != A[right]) {            visited[A[left]] = false;            left++;        }        long long n = right - tmp_left;        ret = ret + ((n << 1) - left + tmp_left) * (left - tmp_left + 1) / 2;        left++;    }    long long n = right - left;    ret = (ret + n * (n+1) / 2);    if (ret < kDistinctSlices) {        return (int) ret;    }    else {        return kDistinctSlices;    }}


0 0
原创粉丝点击