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虚拟机》之(二、垃圾收集器与内存分配策略)

    程序计数器.虚拟机栈.本地方法栈3个区域随线程而生,随线程而灭,这几个区域的内存分配和回收都具备确定性,不需要过多考虑回收的问题,因为方法结束或者线程结束时,内存自然就跟着回收了,而java堆和方法区 ...

  2. Redis:RedisHelper(5)

    /// <summary> /// Redis 助手 /// </summary> public class RedisHelper { /// <summary> ...

  3. nginx与php之间的交互方式

    1.  2种方式 TCP的socket  跟 UNIX的socket 2.TCP的socket  首先进入容器然后修改nginx下的配置文件 3. 修改/usr/local/nginx/conf/ng ...

  4. 【git】git中使用https和ssh协议的区别以及它们的用法

    git可以使用四种主要的协议来传输资料: 本地协议(Local),HTTP 协议,SSH(Secure Shell)协议及 git 协议.其中,本地协议由于目前大都是进行远程开发和共享代码所以一般不常 ...

  5. 小米oj 数组差(挺好的题)

     数组差 序号:#46难度:困难时间限制:1000ms内存限制:10M 描述 给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组元素和的差的绝对值 |SUM(A) - SUM(B)| 最大. ...

  6. 一 、Linux基础命令及使用帮助

    linux的哲学思想: 一切皆文件: 把几乎所有资源,包括硬件设备都组织为文件系统 由众多单一目的小程序组成:一个程序只实现一个功能,而且要做好 组合小程序完成复杂任务 尽量避免跟用户交互 目的:实现 ...

  7. loj6519 魔力环

    解题思路 考虑顺时针旋转 \(i\) 步得到的结果,根据Burnside引理,有 \[ Ans=\frac{\sum\limits_{i=0}^{n-1}C(i)}{n} \] \(C(i)\) 为旋 ...

  8. axios 是如何封装 HTTP 请求的

    原载于 TutorialDocs 网站的文章<How to Implement an HTTP Request Library with Axios>.译者:zhangbao90shttp ...

  9. nvm临时版本和永久版本

    nvm use 8.15.1//临时版本 nvm alias default 8.15.1//永久版本

  10. centos7下面安装tomcat

    前言 对于一个新安装的 centos 系统来说,是没有 tomcat 服务器的.用下面的命令可以查看 tomcat 服务的状态. systemctl status tomcat.service//或者 ...