2013-04-04 115 views
0

我試圖製作一個程序來檢查一個數組是否包含來自另一個數組的所有數組值。所以,如果這是真的,程序將返回1使用它的值。如果不是這樣,它將返回0(我將它命名爲p)。儘管我沒有做出這個計劃。你可以幫我嗎?檢查數組是否包含來自另一個數組中的所有數組值C

+1

提示:如果兩個數組分選,你怎麼能輕鬆地測試一個是否包含其他? – Zeta 2013-04-04 21:16:03

回答

1
#include <stdio.h> 

int isSubset(int arr1[], int arr2[], int m, int n) 
{ 
    int i = 0; 
    int j = 0; 
    for (i=0; i<n; i++) 
    { 
     for (j = 0; j<m; j++) 
     { 
      if(arr2[i] == arr1[j]) 
       break; 
     } 

     /* If the above inner loop was not broken at all then 
      arr2[i] is not present in arr1[] */ 
     if (j == m) 
      return 0; 
    } 

    /* If we reach here then all elements of arr2[] 
     are present in arr1[] */ 
    return 1; 
} 

int main() 
{ 
    int arr1[] = {11, 1, 13, 21, 3, 7}; 
    int arr2[] = {11, 2, 7, 1}; 

    int m = sizeof(arr1)/sizeof(arr1[0]); 
    int n = sizeof(arr2)/sizeof(arr2[0]); 

    if(isSubset(arr1, arr2, m, n)) 
     printf("arr2[] is subset of arr1[] "); 
    else 
     printf("arr2[] is not a subset of arr1[]");  

    getchar(); 
    return 0; 
} 



Ideone鏈接和運行http://ideone.com/4u9oQm

+0

時間複雜度:O(m * n) – 2013-09-16 16:08:17

相關問題