【leetcode】765. 情侣牵手

 

#define min(a,b) ((a)<(b))?(a):(b)

bool isLovers(int i, int j){
    if (abs(i - j) == 1){
        int minVal = min(i, j);
        if (minVal % 2 == 0){
            return true;
        }
    }
    return false;
}
int minSwapsCouples(int* row, int rowSize){
    int pst[60], i, cnt = 0;
    int hash[60] = { 0 };
    for (i = 0; i<rowSize; i++){
        pst[row[i]] = i;
    }
    for (i = 0; i<rowSize - 1; i += 2){
        if (hash[row[i]])
            continue;
        if ( isLovers(row[i], row[i+1]) ){
            hash[row[i]] = hash[row[i + 1]] = 1;
            continue;
        }
        else{
            int lovers = (row[i] % 2) ? row[i] - 1 : row[i] + 1;
            int num = (pst[lovers] % 2) ? row[pst[lovers] - 1] : row[pst[lovers] + 1];
            if (isLovers(row[i + 1], num)){
                hash[row[i]] = hash[row[i + 1]] = hash[lovers] = hash[num] = 1;
            }
            else{
                hash[row[i]] = hash[lovers] = 1;
                row[pst[lovers]] = row[i + 1];
                pst[row[i+1]]=pst[lovers];
            }
        }
        cnt++;

    }
    return cnt;
}

 

posted @ 2021-02-21 11:39  温暖了寂寞  阅读(69)  评论(0编辑  收藏  举报