zoukankan      html  css  js  c++  java
  • LeetCode-765 情侣牵手/交换座位

     


    参考代码
     1 import java.util.Scanner;
     2 
     3 public class Test {
     4     public static void main(String[] args) {
     5         Scanner in = new Scanner(System.in);
     6         int n = in.nextInt();
     7         int[] row = new int[2 * n];
     8         int sum = 0;
     9         for (int i = 0; i < row.length; i++) {
    10             row[i] = in.nextInt();
    11         }
    12         System.out.println(minSwapsCouples(row));
    13 
    14     }
    15     public static int minSwapsCouples(int[] row) {
    16         int n=0;
    17         //只需要遍历下标为偶数的座位,每次+2,奇数的座位可由交换座位匹配好
    18         for(int i=0;i<=row.length-2;i+=2){
    19             int j;
    20             //判断下标i的情侣是多少
    21             j=row[i]%2==0?row[i]+1:row[i]-1;
    22             //若下一个座位的不是该情侣
    23             if(row[i+1]!=j){
    24                 //需要进行交换座位
    25                 n++;
    26                 //找到该情侣,进行交换
    27                 for(int m=i+2;m<row.length;m++){
    28                     // 如果m从0开始找的话,算法复杂度高,会超时,应该从i+2开始找!
    29                     if(row[m]==j){
    30                         swap(row,m,i+1);
    31                         break; // 交换后记得break
    32                     }
    33                 }
    34             }
    35         }
    36         return n;
    37     }
    38     
    39     //交换
    40     private static void swap(int[] a,int i,int j){
    41         int tmp=a[i];
    42         a[i]=a[j];
    43         a[j]=tmp;
    44     }
    45 
    46 }
    Demo 1
    
    
    

    参考博客:https://www.cnblogs.com/lyh28/p/10630649.html

  • 相关阅读:
    51nod1042
    51nod1009
    分库分表Mycat总结
    RocketMQ事务消息实现分析
    RocketMQ消费模式
    mysql中的隐式转换总结
    EXPLAIN用法和结果分析
    MySQL日期时间处理函数总结
    RocketMQ在windows环境下的安装
    深入分析Synchronized原理
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/12811083.html
Copyright © 2011-2022 走看看