Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm chỉ mục phần tử thừa trong mảng đã sắp xếp trong C++


Cho hai mảng đã sắp xếp arr1 (size n) và arr2 (size n+1) giống nhau trừ một phần tử thừa. Nhiệm vụ: tìm chỉ mục phần tử thừa trong mảng lớn hơn.

Ví dụ:

Đầu vào: arr1[n] = {3, 5, 7, 8, 9, 12}
arr2[n+1] = {3, 4, 5, 7, 8, 9, 12}

Đầu ra: 1

Giải thích: Phần tử 4 thừa ở chỉ mục 1.

Phương pháp giải

Cách 1: Tìm kiếm tuyến tính - So sánh từng cặp phần tử, dừng khi khác nhau.

Cách 2: Tìm kiếm nhị phân - So sánh giữa, nếu bằng nhau thì phần tử thừa ở bên phải, ngược lại bên trái. O(log n).

Cách 3: Hiệu tổng - Trừ tổng arr2 - arr1 = giá trị thừa. Tìm chỉ mục của giá trị đó trong arr2.

Chương trình minh họa (3 cách)

Ví dụ 1: Tuyến tính

#include <iostream>
using namespace std;

int findExtraElement(int arr1[], int arr2[], int n) {
    int i;
    for (i = 0; i < n; i++)
        if (arr1[i] != arr2[i])
            break;
    return i;
}

int main() {
    int arr1[] = {3, 5, 7, 8, 9, 12};
    int arr2[] = {3, 4, 5, 7, 8, 9, 12};
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int extraIndex = findExtraElement(arr1, arr2, n);
    cout << "The extra element is at index (" << extraIndex << ") and the value is " << arr2[extraIndex];
    return 0;
}

Kết quả

The extra element is at index (1) and the value is 4

Ví dụ 2: Nhị phân

#include <iostream>
using namespace std;

int findExtraElement(int arr1[], int arr2[], int n) {
    int extraIndex = n;
    int start = 0, end = n - 1;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (arr2[mid] == arr1[mid])
            start = mid + 1;
        else {
            extraIndex = mid;
            end = mid - 1;
        }
    }
    return extraIndex;
}

int main() {
    int arr1[] = {3, 5, 7, 8, 9, 12};
    int arr2[] = {3, 4, 5, 7, 8, 9, 12};
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int extraIndex = findExtraElement(arr1, arr2, n);
    cout << "The extra element is at index (" << extraIndex << ") and the value is " << arr2[extraIndex];
    return 0;
}

Kết quả

The extra element is at index (1) and the value is 4

Ví dụ 3: Hiệu tổng

#include <iostream>
using namespace std;

int calcArraysum(int arr[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
    return sum;
}

int findExtraElement(int arr1[], int arr2[], int n) {
    int extraValue = calcArraysum(arr2, n + 1) - calcArraysum(arr1, n);
    for (int i = 0; i < n; i++) {
        if (arr2[i] == extraValue)
            return i;
    }
    return -1;
}

int main() {
    int arr1[] = {3, 5, 7, 8, 9, 12};
    int arr2[] = {3, 4, 5, 7, 8, 9, 12};
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int extraIndex = findExtraElement(arr1, arr2, n);
    cout << "The extra element is at index (" << extraIndex << ") and the value is " << arr2[extraIndex];
    return 0;
}

Kết quả

The extra element is at index (1) and the value is 4