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 ...
随机推荐
- HDU 4085 斯坦纳树+DP
https://cn.vjudge.net/problem/HDU-4085 给你n,m,k ,分别表示有n个点,m条边,每条边有一个权值,表示修复这条边需要的代价 从前k个点中任取一个使其和后k个点 ...
- django国际化的简单设置
设置国际化的具体步骤: 一.国际化 1)效果:针对不同的国家的人可以配置不同的语言(一般是英文和中文, English Chinese) 2)目的:增加项目的用户量 3)难度:不难 比较费劲的就是 ...
- C#中 委托和事件的关系
首先,委托 是一个好东西.按我的理解,委托 是针对 方法 的更小粒度的抽象.比较interface,他精简了一些代码.使得 订阅-通知 (观察者模式)的实现变得非常简洁. 关于事件,我最初的理解是:事 ...
- 回顾了下shell 编程的一些细节
回顾了一些细节 shell 的通配符扩展 * ? [] [^xxxx] {aaa,bbb} 子进程 more `grep -l POSIX *` more $(grep -l ...
- 统计连接到主机前十的ip地址和连接数
常用脚本–tcp #!/bin/bash # #******************************************************************** #encodi ...
- 第四章 Jinja2模版
模板简介: 在之前的章节中,视图函数只是直接返回文本,而在实际生产环境中的页面大多是带有样式和复杂逻辑的HTML代码,这可以让浏览器渲染出非常漂亮的页面.目前市面上有非常多的模板系统,其中最知名好用的 ...
- Hive中遇到全角
今天在梳理银行SQL业务的时候出现了一个全角的问题:两个种代码 都可以 使用了UDF函数解决 package 广发; import org.apache.hadoop.hive.ql.exec.Des ...
- Codeforces工具总结
本总结针对Linux用户,由于笔者一直使用Ubuntu系统打Codeforces 打Codeforcecs,想精确能力,打出究极罚时,可以考虑以下套餐 套餐一 vim选手 使用vim + fish + ...
- PHP mysqli_field_seek() 函数
定义和用法 mysqli_field_seek() 函数把字段指针设置为指定字段的偏移量. 设置结果集中第一个字段(列)的字段指针,然后通过 mysqli_fetch_field() 获取字段信息并输 ...
- QueryList之flatten方法
正确用法: $data = $ql->get($url)->query()->getData();$data = $data->flatten()->all(); 注意: ...