Nếu mảng của bạn không được sắp xếp, độ phức tạp của trường hợp xấu nhất khi loại bỏ mảng sử dụng giải pháp trực quan là O (n) (mặc dù bạn có thể tăng điều này nếu sắp xếp mảng trước), vì bạn cần để kiểm tra toàn bộ mảng liệu một phần tử có tồn tại hay không.
Ví dụ về trường hợp xấu nhất:
array a1 = [1, 3, 4, 5, 8];
array a2 = [8, 5, 4, 3, 1];
Nếu mảng của bạn được sắp xếp, sau đó mức độ phức tạp thời gian trường hợp xấu nhất là O (n + m) (pseudo-code):
int i = 0;
for(int j = 0; i < a1.size && j < a2.size;){
if(a1[i] == a2[j])
++i, ++j; // exclude this element
if(a1[i] < a2[j]){
a3.push(a1[i]); // include this element
++i;
}
if(a1[i] > a2[j])
++j; // ignore lesser elements
}
while(i < a1.size)
a3.push(a1[i]);
UPDATE-Wall -Wextra -pedantic
Mã C:
#include <stdio.h>
#include <malloc.h>
/**
* The following function excludes values from an array using another arrays values.
* Note that this version won't exclude multiple values, for this you have to drop
* '++j' in line 25.
*
* \param[in] from Original sorted array
* \param[in] from_length Original array length
* \param[in] what Sorted array including the excluding values
* \param[in] what_length self describing
* \param[out] result_length the lenght of the new array - a value lesser 0 indicates an error.
*/
int* exclude(int* from, int from_length, int* what, int what_length, int* result_length){
int i,j,k;
int* result = (int*) malloc(sizeof(int)*from_length);
if(result == NULL){
*result_length = -1;
return NULL;
}
for(i = j = k = 0; i < from_length && j < what_length;){
if(from[i] == what[j])
++i, ++j; /* exclude this element - to enable multiple exclusion drop '++j'
4,4,5,6 /4 --> 5,6 */
if(from[i] < what[j])
result[k++] = from[i++];
if(from[i] > what[j])
++j; /* ignore lesser elements */
}
while(i < from_length)
result[k++] = from[i++];
if(k < from_length){
int* tmp = (int*) realloc(result,sizeof(int)*k);
if(tmp == NULL){
/* either error handling or returning result */
}else{
result = tmp;
}
}
*result_length = k;
return result;
}
int main(){
int a[6] = {1,2,3,4,5,6};
int b[3] = {2,4,5};
int result_length;
int i;
int *c = exclude(a,6,b,3,&result_length);
for(i = 0; i < result_length; ++i)
printf("%i ",c[i]);
free(c);
return 0;
}
Điều này sẽ r esult trong một thời gian phức tạp tồi tệ nhất của O(n+m)
đối với các mảng được sắp xếp và O(n log n + m log m)
đối với các mảng không được sắp xếp (sắp xếp cả hai, sử dụng hàm được cung cấp ở trên).
tôi sợ đây là một cách để đi. Ngoại trừ ... Nếu bạn đã sắp xếp mảng, bạn luôn có thể di chuyển "điểm bắt đầu" và bắt đầu từ 'j = something' ... – Vyktor