1067.Sort with Swap(0,i) java

 

题目大意:每次只能用0交换,计算得到升序的最少交换次数 

思路:观察现在的顺序与升序,0占用了谁的位置就和谁先交换

样例分析:

升序(第一行)

现在状态(第二行)

0 1 2 3 4 5 6 7 8 9
3 5 7 2 6 4 9 0 8 1

第一次交换0 7

0 1 2 3 4 5 6 7 8 9
3 5 0 2 6 4 9 7 8 1

第二次交换0 2

0 1 2 3 4 5 6 7 8 9
3 5 2 0 6 4 9 7 8 1

第三次交换0 3 

0 1 2 3 4 5 6 7 8 9
0 5 2 3 6 4 9 7 8 1

目前出现一个问题,0提前归位了,但必须要用0和别人交换,于是找到第一个未归位的与0交换(如果找归位的前面的工作就白做了) 

第四次交换0 5

0 1 2 3 4 5 6 7 8 9
5 0 2 3 6 4 9 7 8 1

 第五次交换0 1

0 1 2 3 4 5 6 7 8 9
5 1 2 3 6 4 9 7 8 0

 第六次交换0 9

0 1 2 3 4 5 6 7 8 9
5 1 2 3 6 4 0 7 8 9

第七次交换0 6

0 1 2 3 4 5 6 7 8 9
5 1 2 3 0 4 6 7 8 9

第八次交换0 4

0 1 2 3 4 5 6 7 8 9
5 1 2 3 4 0 6 7 8 9

第九次交换0 5 结束

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n= scanner.nextInt();
        ArrayList<Integer>arrayList=new ArrayList<>();
        int original_count=0;//除零外,一开始没有在自己位置上的个数
        int count=0;//需要的操作数
        for (int i=0;i<n;i++){
            arrayList.add(scanner.nextInt());
            if (arrayList.get(i)!=i&&i!=0){
                original_count++;
            }
        }
        while (original_count>0 ){//还没全部归位
              if (arrayList.get(0)!=0){//0没有提前归位
                int index=arrayList.indexOf(0);
                int temp=arrayList.indexOf(index);
                arrayList.set(index,index);
                arrayList.set(temp,0);
                original_count--;
                count++;
            }
            else {//0提前归位
                int j=1;
                for (;;j++){
                    if (arrayList.get(j)!=j){
                        break;
                    }
                }
                int temp=arrayList.get(j);
                arrayList.set(j,0);
                arrayList.set(0,temp);
                count++;
            }
        }
        System.out.println(count);
    }
}





 

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值