leetCode(Using C)——760. Find Anagram Mappings

純愛楓若情發表於2018-01-16

Description:

Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A.

We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.

These lists A and B may contain duplicates. If there are multiple answers, output any of them.

Example:

given:

A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
We should return
[1, 4, 3, 2, 0]
as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.

Note:

  1. A, B have equal lengths in range [1, 100].

  2. A[i], B[i] are integers in range [0, 10^5].

If you want to solve the problem, you can visite the web site.click me

Code:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* anagramMappings(int* A, int ASize, int* B, int BSize, int* returnSize) {
    int *p;
    p = (int *)malloc(sizeof(int)*ASize);
    int flag[ASize];
    memset(flag, 0, sizeof(flag));

    *returnSize = ASize;
    for(int i=0; i<ASize; i++){
        for(int j=0; j<BSize; j++){
            if(A[i]==B[j]&&flag[j]==0){
                p[i]=j;
                // printf("p[%d]=%d\n",i,j);
                flag[j]=1;
                break;  //一定別忘了break!
            }
        }
    }
    return p;
}

感想

刷題一定要看清題目讓你返回什麼!博主一開始就寫對了,但是就是在提交的時候一直結果都是空,不知道哪個地方有問題。後來仔細的研究了以下程式碼前面的幾句說明性的話。

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/

第一句跟你說,讓你將返回的陣列大小放在returnSize中。第二句讓你動態的分配陣列,不要直接用定義陣列的方法。注意到這兩點,就很簡單了。

相關文章