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 ...
随机推荐
- 对List<Map>里的map的某个属性重复的值进行处理的方法
package test; import java.util.*;import java.util.stream.Collectors; public class Test5 { public sta ...
- Eclipse中给jar包导入JavaDoc注释文档的方法
原文链接:http://www.apkbus.com/android-124056-1-1.html 第一步:将jar加入到Referenced Libraries 右键点击jar --> 选择 ...
- setTimeout设置为0 为啥不能立马执行
setTimeout(function(){}, timer) 是指延时执行.第一个参数是回调函数,第二个参数是指延时多久执行回调函数. setTimeout(function(){console.l ...
- String字符串反转
new StringBuffer("abcde").reverse().toString(); 通过char数组进行转换 package com.test.reverse; pub ...
- Peter Shirley Ray Tracing in One Weekend(上篇)
Peter Shirley-Ray Tracing in One Weekend (2016) 原著:Peter Shirley 本书是Peter Shirley ray tracing系列三部曲的第 ...
- 解决从其他地方拷贝过来的Android项目在本机不能运行(报错)的问题
这个问题一般是由gradle版本不同引起的.要解决可以这样: 一.在确保本机Android studio 正常使用的情况下,在本机新建一个Android项目 二.在文件夹中打开新建的Android项目 ...
- IAT表和导入表
1.关于IAT(import address table)表 当exe程序中调用dll中的函数时,反汇编可以看到,call后面并不是跟的实际函数的地址,而是给了一个地址:
- Vivado与Modelsim联合仿真
[转载]: 1:https://blog.csdn.net/weixin_37603007/article/details/82823965 2:https://blog.csdn.net/Piece ...
- Luogu P5048 [Ynoi2019模拟赛]Yuno loves sqrt technology III 分块
这才是真正的$N\sqrt{N}$吧$qwq$ 记录每个数$vl$出现的位置$s[vl]$,和每个数$a[i]=vl$是第几个$vl$,记为$P[i]$,然后预处理出块$[i,j]$区间的答案$f[i ...
- 用python实现的简易记牌器的demo
实现功能很简单: 初始时 1到10 以及 jkq各 4张,大小王 共两张 只要输入相应的牌号:1到10,例如 >>1 J.K.Q :例如>>j >> ...