容易想到,直接遍历vector,i += 2 ;将偶数位置的数交换为当前i的情侣,遍历可得
int find(vector<int>& row,int index,int value) { for (int i = index+1; i < row.size(); i++) { if (row[i] == value) return i; } return index; } class Solution { public: int minSwapsCouples(vector<int>& row) { for (auto &i : row) i /= 2; int count = 0; for (int i = 0; i < row.size(); i += 2) { // 需要交换的情况 if (row[i] != row[i + 1]) { int ex = find(row,i+1, row[i]); std::swap(row[i + 1], row[ex]); count++; } } return count; } };
这样效率不高:
尝试用hash优化搜索效率:(建立unordered_map<int,int> 能以常数时间找到value对应位置,然后进行交换)
class Solution { public: int minSwapsCouples(vector<int>& row) { unordered_map<int, int> map; for (int i = 0; i < row.size(); i++) map[row[i]] = i; int count = 0; for (int i = 0; i < row.size(); i += 2) { // 需要交换的情况 if (row[i]>>1 != row[i + 1]>>1) { int value = row[i] % 2 ? row[i] - 1 : row[i] + 1; int ex = map[value]; map[row[i+1]] = ex; std::swap(row[i + 1], row[ex]); count++; } } return count; } };
效果如下: