Embedded System Interview: MissingInteger

Hot

Hiển thị các bài đăng có nhãn MissingInteger. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn MissingInteger. Hiển thị tất cả bài đăng

Chủ Nhật, 19 tháng 1, 2020

MissingInteger

tháng 1 19, 2020 0
Write a function:

    int solution(vector<int> &A);

that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Write an efficient algorithm for the following assumptions:

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


#include <unordered_map>

int solution(vector<int> &A) {
    // write your code in C++11 (g++ 4.8.2)
    unordered_map<int, int> map;
    
    for (int i = 0; i < int(A.size()); i++) {
        if (A[i] > 0) {
            map[A[i]] = i;    
        }
    }
    
    for (int i = 1; i < int(map.size() + 1); i++) {
        if (map.find(i) == map.end()) return i;     
    }
    
    return int(map.size() + 1);
}
Read More
Thường mất vài phút để quảng cáo xuất hiện trên trang nhưng thỉnh thoảng, việc này có thể mất đến 1 giờ. Hãy xem hướng dẫn triển khai mã của chúng tôi để biết thêm chi tiết. Ðã xong