题解 | #有序序列判断#

有序序列判断

https://www.nowcoder.com/practice/22e87f8a8d764a6582710f38d1b40c6e

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        // 定义两个辅助array 用来实现array 的升序和降序排列
        int []arr = new int[N];
        int []arrASC = new int[N];
        int []arrDESC = new int[N];

        for (int i = 0; i < arr.length; i++) {
            arr[i] = arrASC[i] = arrDESC[i] = sc.nextInt();
        }
        // 调用bubblesort()方法实现升序和降序
        bubblesortASC(arrASC);
        bubblesortDESC(arrDESC);
        //调用Arrays.equals()方法判断
        // 底层源码是按 地址--是否非空--长度--每个元素进行判断
        if(Arrays.equals(arr,arrASC)||Arrays.equals(arr,arrDESC)){
            System.out.print("sorted");
        }else{
            System.out.print("unsorted");
        }

    }
    // 冒泡排序(升序)
    public static int[] bubblesortASC(int []arr) {
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
    // 冒泡排序(降序)
    public static int[] bubblesortDESC(int []arr) {
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1; j++) {
                if (arr[j] < arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
}

全部评论

相关推荐

理智的马里奥不愿再收感谢信:这小米咱是非去不可了是吗?
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务