笔试题算法系列(八)百度有趣的排序

[编程题] 有趣的排序

时间限制:1秒

空间限制:32768K

度度熊有一个N个数的数组,他想将数组从小到大 排好序,但是萌萌的度度熊只会下面这个操作:
任取数组中的一个数然后将它放置在数组的最后一个位置。
问最少操作多少次可以使得数组从小到大有序?
输入描述:
首先输入一个正整数N,接下来的一行输入N个整数。(N <= 50, 每个数的绝对值小于等于1000)
输出描述:
输出一个整数表示最少的操作次数。
输入例子1:
4
19 7 8 25
输出例子1:
2

代码如下:
 1 import java.lang.Math;
 2 import java.util.Arrays;
 3 import java.util.HashMap;
 4 import java.util.Scanner;
 5 
 6 public class Main{
 7     public static void main(String[] args){
 8         Scanner sc = new Scanner(System.in);
 9         String[] line;
10         while(sc.hasNext()){
11             line = sc.nextLine().split(" ");
12             int n = Integer.parseInt(line[0]);
13              line = sc.nextLine().split(" ");
14             int[] data = new int[n];
15             int min = Integer.MIN_VALUE;
16             int minIndex = 0;
17             for(int i=0; i<n; i++){
18                 data[i]= Integer.parseInt(line[i]);
19                 min = Math.min(min,data[i]);
20                 minIndex = i;
21             }
22             HashMap dataIndex = new HashMap();
23             for(int i=0; i<n; i++){
24                  dataIndex.put(data[i],i);
25             }
26             Arrays.sort(data);
27             int maxIndex = n;
28             int count = 0;
29             for(int i=0; i<n-1; i++){
30                if((int)dataIndex.get(data[i])>(int)dataIndex.get(data[i+1])){
31                   count++;
32                   dataIndex.put(data[i+1],maxIndex++);
33                }
34             }
35             System.out.println(count);
36         }
37         sc.close();
38     }
39 }

猜你喜欢

转载自www.cnblogs.com/haimishasha/p/10639226.html
今日推荐