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的更多相关文章

  1. 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 ...

  2. Reorder array to construct the minimum number

    Construct minimum number by reordering a given non-negative integer array. Arrange them such that th ...

  3. 【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 ...

  4. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  5. [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 ...

  6. Leetcode: Minimum Number of Arrows to Burst Balloons

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  7. 452. Minimum Number of Arrows to Burst Balloons——排序+贪心算法

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Java入门第二季——第4章 多态

    第4章 多态 多态性是允许你将父对象设置成为和一个或更多的他的子对象相等的技术,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作 4-1 Java 中的多态 注意:不能通过父类的引 ...

  2. MyBatis-11-一对多处理

    11.一对多处理 比如:一个老师拥有多个学生! 对于老师而言,就是一对多的关系! 环境搭建 环境搭建,和刚才一样 实体类 @Data public class Teacher { private in ...

  3. Series拼接回DataFrame

    从这样的表,如何计算一行汇总层拼接回去

  4. docker 共享卷

    宿主机与容器共享存储 [root@docker02 ~]# docker run -it -v /var/webroot:/abc 192.168.1.21:5000/busybox # 宿主机文件 ...

  5. python中模块、包、库的区别和使用

    模块:就是.py文件,里面定义了一些函数和变量,需要的时候就可以导入这些模块. 包:在模块之上的概念,为了方便管理而将文件进行打包.包目录下第一个文件便是 __init__.py,然后是一些模块文件和 ...

  6. Educational Codeforces Round 33 (Rated for Div. 2) B题

    B. Beautiful Divisors Recently Luba learned about a special kind of numbers that she calls beautiful ...

  7. 第一次尝试学习java 安装jdk 与配置环境变量 写第一个java程序 并运行

    第一次学习java,今天知道了java之父叫  詹姆斯.高司令 其它的记不住太多,首先我们先来安装jdk 百度搜索jdk12   (现在的jdk为12版本)安装稳定版 找到javaSE12X..  下 ...

  8. heartrbeat实现web服务器高可用

    今天的内容是用heartbeat实现web服务器高可用 一.简介: heartbeat的工作原理:heartbeat最核心的包括两个部分,心跳监测部分和资源接管部分,心跳监测可以通过网络链路和串口进行 ...

  9. django快速实现完整登录系统,把登陆注册串在一起并增加cookie(六)

    1.使用之前创建的项目和应用  mysite3 account 2.使用之前的数据库构造 class User(models.Model): username=models.CharField(max ...

  10. http协议格式详解

    参考:https://www.jianshu.com/p/8fe93a14754c 一.URI结构 HTTP使用统一资源标识符(URI)来传输数据和建立连接.URL(统一资源定位符)是一种特殊种类的U ...