浪潮提前批Java笔试大题

第一题最少搬动石头次数,0(n)复杂度,AC100

/*
沙滩按照线型摆放着n个大小不一的球形石头,已知第i个石头的半径为ri,且不存在两个石头有相同的半径。为了使石头的摆放更加美观,现要求摆放的石头的半径从左往右依次递增。因此,需要对一些石头进行移动,每次操作可以选择一个石头,并把它放在剩下n−1个石头在最左边或最右边。问最少需要操作多少次才能将这n个石头的半径变成升序?
输入
第一行一个整数n,表示石头的个数。(1 <= n <= 100000)
第二行n个整数,表示从左往右石头的半径r1,r2,…,rn。(1 <= ri <= n),且保证不存在两个不同的石头拥有相同的半径。
输出
最少操作次数样例输入
5
4 1 2 5 3
样例输出
2
*/
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()){
            int m = sc.nextInt();
            int []arr = new int[m];
            for(int i = 0; i < m; i ++){
                arr[i] = sc.nextInt();
            }
            int[] dp = new int[m + 1];
            int res = 0;
            for(int num : arr) {
                dp[num] = dp[num - 1] + 1;
                res = Math.max(dp[num], res);
            }
            System.out.println(m - res);
        }
    }
}

第二题被砍掉的树,0(n)复杂度,AC100

/*
某条街道两侧分别种植了一排树木,并按如下编号:
1 3 5 7 … 45 47 49 … 99
2 4 6 8 … 46 48 50 … 100
但是有一些树被砍去,希望你能找出一边最长的连续的大树。
输入
第一行一个整数N
第二行N个整数表示被砍去树的编号
输出
M 和 X(表示从第M棵大树开始,共有连续的X棵大树,如果有多个解,输出M最小的解即可)
样例输入
5
9 15 27 35 6
样例输出
8 47
*/
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()) {
            int m = sc.nextInt();
            int[] arr = new int[m + 2];
            for (int i = 0; i < m; i++) {
                arr[i] = sc.nextInt();
            }
            arr[m] = 101;
            arr[m + 1] = 102;
            Arrays.sort(arr);
            int[] res = new int[2];
            int preOdd = -1;
            int preEven = 0;
            for (int num : arr) {
                if (num % 2 == 1) {
                    int tmp = (num - preOdd) / 2 - 1;
                    if (tmp > res[1]) {
                        res[1] = tmp;
                        res[0] = preOdd + 2;
                    }
                    preOdd = num;
                } else {
                    int tmp = (num - preEven) / 2 - 1;
                    if (tmp > res[1]) {
                        res[1] = tmp;
                        res[0] = preEven + 2;
                    }
                    preEven = num;
                }
            }
            System.out.println(res[0] + " " + res[1]);
        }
    }
}
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值