其他分享
首页 > 其他分享> > Min swaps to sort array

Min swaps to sort array

作者:互联网

Given an array with distinct numbers, return an integer indicating the minimum number of swap operations required to sort the array into ascending order. 

Example 1:

Input: [5, 1, 3, 2]
Output: 2
Explanation: [5, 1, 3, 2] -> [2, 1, 3, 5] -> [1, 2, 3, 5]

Example 2:

Input: [1, 3, 2]
Output: 1
Explanation: [1, 3, 2] -> [1, 2, 3]
分析:
先把原数组保存一份,然后对另一份排序,并且把原数组的值与index保存一份。这样,我们需要得到某个数的位置的时候,直接通过map得到。

 1 public class Solution {
 2     public int minSwaps(int[] elems) {
 3         int counter = 0;
 4         Map<Integer, Integer> map = buildMap(elems);
 5         int[] copy = new int[elems.length];
 6         System.arraycopy(elems, 0, copy, 0, elems.length);
 7         Arrays.sort(elems);
 8 
 9         for (int i = 0; i < copy.length; i++) {
10             if (copy[i] != elems[i]) {
11                 swap(copy, i, map.get(elems[i]), map);
12                 counter++;
13             }
14         }
15         return counter;
16     }
17 
18     private Map<Integer, Integer> buildMap(int[] elems) {
19         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
20         for (int i = 0; i < elems.length; i++) {
21             map.put(elems[i], i);
22         }
23         return map;
24     }
25 
26     private void swap(int[] elems, int i, int j, Map<Integer, Integer> map) {
27         map.put(elems[j], i);
28         map.put(elems[i], j);
29         int temp = elems[j];
30         elems[j] = elems[i];
31         elems[i] = temp;
32     }
33 }

 

 
 

标签:sort,map,swaps,Map,int,elems,length,array,copy
来源: https://www.cnblogs.com/beiyeqingteng/p/11297163.html