- 贪心思想,每一步使得对应元素放到它该放的位置。
- 先将要排序的数组复制一份,然后将其排序,使用哈希表记录排序后的数组对应元素与其对应下标。
- 遍历原数组与排序后的数组,如果对应下标不相等,则根据哈希表记录该元素的下标进行交换。
int getMinSwap(vector &nums)
{
mapmp;
vectorsort_nums(nums);
sort(sort_nums.begin(),sort_nums.end());
for (int i = 0; i
- 注意上述代码中,第二个for循环使用的是while,使用if会跳过某些元素。如下图对比。


- 相关题目
- 先层序遍历获取每层元素,然后对每层元素求有序最小的操作数目。
int minimumOperations(TreeNode* root) {
int depth = 0;
vector>layerContent;
queueque;
if(root)que.push(root);
while(!que.empty()){
int size = que.size();
depth++;
vectortmp;
for(int i = 0; i < size;i++){
TreeNode* node = que.front();
que.pop();
tmp.push_back(node->val);
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
layerContent.push_back(tmp);
}
// 已经获取二叉树的每层元素&层数
int count = 0;
for(int i = 1; i < depth;i++){
count += getMinSwap(layerContent[i]);
}
return count;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25