[网易秋招笔试]第2题字典序题目(数组,思维)

题目


题解

题意:根据m长子序列求长度为n的字典序最小的原序列,原序列元素为1ton;
题解:使用n个数中除子序列外剩余数组成otherNum数组。
两个指针指向两个数组首元素,比较子序列当前元素与otherNum数组当前元素,小的插入新数组,指针右移。

代码

import java.util.Scanner;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        
        int[] subNums=new int[m];
        int[] nums=new int[n];
        int[] otherNums=new int[n-m];
        Set<Integer> set=new HashSet<>();
        for(int i=0;i<m;++i){
            int num=in.nextInt();
            subNums[i]=num;
            set.add(num);
        }
        
        int otherIdx=0;
        for(int i=1;i<=n;++i){
            if(!set.contains(i)){
                otherNums[otherIdx++]=i;
            }
        }
        
        
        //处理
        int idx=0;
        otherIdx=0;
        int subIdx=0;
        while(idx<n&&subIdx<m&&otherIdx<n-m){
            if(subNums[subIdx]<otherNums[otherIdx]){
                nums[idx++]=subNums[subIdx++];
            }else{
                nums[idx++]=otherNums[otherIdx++];
            }
        }    
        while(subIdx<m){
            nums[idx++]=subNums[subIdx++];
        }
        while(otherIdx<n-m){
            nums[idx++]=otherNums[otherIdx++];
        }
        
        //打印
        for(int i=0;i<n-1;++i){
            System.out.print(nums[i]+" ");
        }
        System.out.print(nums[n-1]);
    }
}

posted on 2020-08-08 17:03  coding_gaga  阅读(243)  评论(0编辑  收藏  举报

导航