Minimum number of swaps required to sort an array
https://www.hackerrank.com/challenges/minimum-swaps-2/problem
Minimum Swaps II
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
For example, given the array we perform the following steps:
i arr swap (indices)
0 [7, 1, 3, 2, 4, 5, 6] swap (0,3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6)
5 [1, 2, 3, 4, 5, 6, 7]
It took swaps to sort the array.
Function Description
Complete the function minimumSwaps in the editor below. It must return an integer representing the minimum number of swaps to sort the array.
minimumSwaps has the following parameter(s):
- arr: an unordered array of integers
Input Format
The first line contains an integer, , the size of .
The second line contains space-separated integers .
Constraints
Output Format
Return the minimum number of swaps to sort the given array.
Sample Input 0
4
4 3 1 2
Sample Output 0
3
Explanation 0
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Sample Input 1
5
2 3 4 1 5
Sample Output 1
3
Explanation 1
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Sample Input 2
7
1 3 5 2 4 6 8
Sample Output 2
3
Explanation 2
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
Given an array of n distinct elements, find the minimum number of swaps required to sort the array.
Examples:
Input : {4, 3, 2, 1}
Output : 2
Explanation : Swap index 0 with 3 and 1 with 2 to
form the sorted array {1, 2, 3, 4}.
Input : {1, 5, 4, 3, 2}
Output : 2
// Java program to find minimum number of swaps
// required to sort an array
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.*; class GfG
{
// Function returns the minimum number of swaps
// required to sort the array
public static int minSwaps(int[] arr)
{
int n = arr.length; // Create two arrays and use as pairs where first
// array is element and second array
// is position of first element
ArrayList <Pair <Integer, Integer> > arrpos =
new ArrayList <Pair <Integer, Integer> > ();
for (int i = 0; i < n; i++)
arrpos.add(new Pair <Integer, Integer> (arr[i], i)); // Sort the array by array element values to
// get right position of every element as the
// elements of second array.
arrpos.sort(new Comparator<Pair<Integer, Integer>>()
{
@Override
public int compare(Pair<Integer, Integer> o1,
Pair<Integer, Integer> o2)
{
if (o1.getKey() > o2.getKey())
return -1; // We can change this to make it then look at the
// words alphabetical order
else if (o1.getKey().equals(o2.getKey()))
return 0; else
return 1;
}
}); // To keep track of visited elements. Initialize
// all elements as not visited or false.
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false); // Initialize result
int ans = 0; // Traverse array elements
for (int i = 0; i < n; i++)
{
// already swapped and corrected or
// already present at correct pos
if (vis[i] || arrpos.get(i).getValue() == i)
continue; // find out the number of node in
// this cycle and add in ans
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = true; // move to next node
j = arrpos.get(j).getValue();
cycle_size++;
} // Update answer by adding current cycle.
ans += (cycle_size - 1);
} // Return result
return ans;
}
} // Driver class
class MinSwaps
{
// Driver program to test the above function
public static void main(String[] args)
{
int []a = {1, 5, 4, 3, 2};
GfG g = new GfG();
System.out.println(g.minSwaps(a));
}
}
// This code is contributed by Saksham Seth
Minimum number of swaps required to sort an array的更多相关文章
- the minimum number of bits required to represent x 最小位数
src/math/bits/bits.go:296 // --- Len ---// Len returns the minimum number of bits required to repres ...
- Reorder array to construct the minimum number
Construct minimum number by reordering a given non-negative integer array. Arrange them such that th ...
- 【leetcode】1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
题目如下: Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the ...
- [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- [LeetCode] 452 Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- Leetcode: Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- 452. Minimum Number of Arrows to Burst Balloons——排序+贪心算法
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- [Swift]LeetCode452. 用最少数量的箭引爆气球 | Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- [Swift]LeetCode995. K 连续位的最小翻转次数 | Minimum Number of K Consecutive Bit Flips
In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray o ...
随机推荐
- linux内核无锁缓冲队列kfifo原理
Linux kernel里面从来就不缺少简洁,优雅和高效的代码 比如,通过限定写入的数据不能溢出和内存屏障实现在单线程写单线程读的情况下不使用锁.因为锁是使用在共享资源可能存在冲突的情况下.还用设置b ...
- solr 中文分词相关(转载)
smartcn和ik的对比,来自http://www.cnblogs.com/hadoopdev/p/3465556.html 一.引言: 年的时候,就曾经有项目涉及到相关的应用(Lunce构建全文搜 ...
- BZOJ 3038: 上帝造题的七分钟2 / BZOJ 3211: 花神游历各国 (线段树区间开平方)
题意 给出一些数,有两种操作.(1)将区间内每一个数开方(2)查询每一段区间的和 分析 普通的线段树保留修改+开方优化.可以知道当一个数为0或1时,无论开方几次,答案仍然相同.所以设置flag=1变表 ...
- IDEA 安装与破解(亲测有效)
本文转载:https://blog.csdn.net/g_blue_wind/article/details/74380483 根据以下的流程,顺利安装了最新版本的idea企业版. IDEA 全称 I ...
- Python2.x与3.x版本区别Ⅲ
八进制字面量表示 八进制数必须写成0o777,原来的形式0777不能用了:二进制必须写成0b111. 新增了一个bin()函数用于将一个整https://www.xuanhe.net/数转换成二进制字 ...
- jquery里把数组转换成json的方法
首先来看,jquery里自带的,和json相关的函数: 1.$.parseJSON : 用来解析JSON字符串,返回一个对象. 什么叫“JSON字符串”? 比如: var a={name:&quo ...
- Microsoft.Practices.Unity使用配置文件总是报错The type name or alias could not be resolved.
Type name could not be resolved. Please check config file http://stackoverflow.com/questions/1493564 ...
- 洛谷P2796 Facer的程序
洛谷题目链接 动态规划 我们看题目后知道这是一棵无根树,要求出有多少子树 我们设$f[u][1]$表示选了当前节点$u$的方案数 相反的$f[u][0]$则为不选中$u$ 那么考虑状态转移如下: f[ ...
- AcWing:240. 食物链(扩展域并查集 or 带边权并查集)
动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形. A吃B, B吃C,C吃A. 现有N个动物,以1-N编号. 每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种. 有人用 ...
- 关于AngularJS与其他前端框架混合使用的思考
AngularJS 是一个为动态WEB应用设计的结构框架,拥有双向数据绑定,模板,MVVM,依赖注入,指令5大优点,Angular最有诱惑力的就是数据绑定功能,使用MVC模式进行开发,Angular在 ...