2025年Java機(jī)試題及答案_第1頁
2025年Java機(jī)試題及答案_第2頁
2025年Java機(jī)試題及答案_第3頁
2025年Java機(jī)試題及答案_第4頁
2025年Java機(jī)試題及答案_第5頁
已閱讀5頁,還剩18頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

2025年Java機(jī)試題及答案一、股票交易最大利潤(動態(tài)規(guī)劃)給定一個整數(shù)數(shù)組`prices`,其中`prices[i]`表示第`i`天某股票的價格;整數(shù)`k`表示最多允許完成`k`次交易(一次交易定義為買入并賣出一支股票,即先買入后賣出,且同一時間只能持有一支股票);整數(shù)`fee`表示每筆交易的費(fèi)用(買入和賣出各收取一次`fee`)。請計算在最多`k`次交易的情況下,扣除所有費(fèi)用后的最大利潤。如果不能獲得利潤,返回0。輸入示例1:`prices=[3,1,4,2,5],k=2,fee=1`輸出:5參考答案:```javaimportjava.util.Arrays;publicclassStockProfit{publicintmaxProfit(int[]prices,intk,intfee){intn=prices.length;if(n<2||k==0)return0;if(k>=n/2){intprofit=0;for(inti=1;i<n;i++){if(prices[i]>prices[i1]+2fee){profit+=prices[i]prices[i1]2fee;}}returnMath.max(profit,0);}int[][][]dp=newint[n][k+1][2];for(intj=0;j<=k;j++){Arrays.fill(dp[0][j],Integer.MIN_VALUE/2);}dp[0][0][0]=0;dp[0][0][1]=-prices[0]fee;for(inti=1;i<n;i++){for(intj=0;j<=k;j++){dp[i][j][0]=Math.max(dp[i1][j][0],dp[i1][j][1]+prices[i]fee);if(j>0){dp[i][j][1]=Math.max(dp[i1][j][1],dp[i1][j1][0]prices[i]fee);}else{dp[i][j][1]=dp[i1][j][1];}}}intmax=0;for(intj=0;j<=k;j++){max=Math.max(max,dp[n1][j][0]);}returnMath.max(max,0);}}```解析:動態(tài)規(guī)劃狀態(tài)定義為`dp[i][j][0/1]`,表示第`i`天結(jié)束時,完成`j`次交易且是否持有股票的最大利潤。通過狀態(tài)轉(zhuǎn)移處理買入、賣出操作的費(fèi)用扣除,當(dāng)`k`較大時優(yōu)化為無限次交易邏輯,避免冗余計算。二、根據(jù)前序和后序遍歷重建二叉樹給定兩個整數(shù)數(shù)組`preorder`(前序遍歷)和`postorder`(后序遍歷),數(shù)組元素互不相同。請重建該二叉樹并返回根節(jié)點(diǎn),若存在多種可能則返回任意一種。輸入示例:`preorder=[1,2,4,5,3,6,7],postorder=[4,5,2,6,7,3,1]`輸出:根節(jié)點(diǎn)為1的二叉樹(結(jié)構(gòu):1左子2,右子3;2左子4,右子5;3左子6,右子7)參考答案:```javaimportjava.util.HashMap;importjava.util.Map;classTreeNode{intval;TreeNodeleft;TreeNoderight;TreeNode(intval){this.val=val;}}publicclassTreeReconstructor{publicTreeNodeconstructFromPrePost(int[]preorder,int[]postorder){Map<Integer,Integer>postMap=newHashMap<>();for(inti=0;i<postorder.length;i++){postMap.put(postorder[i],i);}returnbuild(preorder,0,preorder.length1,postorder,0,postorder.length1,postMap);}privateTreeNodebuild(int[]pre,intpreStart,intpreEnd,int[]post,intpostStart,intpostEnd,Map<Integer,Integer>postMap){if(preStart>preEnd)returnnull;TreeNoderoot=newTreeNode(pre[preStart]);if(preStart==preEnd)returnroot;intleftChildVal=pre[preStart+1];intleftIndex=postMap.get(leftChildVal);intleftSize=leftIndexpostStart+1;root.left=build(pre,preStart+1,preStart+leftSize,post,postStart,leftIndex,postMap);root.right=build(pre,preStart+leftSize+1,preEnd,post,leftIndex+1,postEnd1,postMap);returnroot;}}```解析:利用前序首元素為根、后序尾元素為根的特性,通過前序次元素確定左子節(jié)點(diǎn)位置,分割后序數(shù)組得到左右子樹范圍,遞歸構(gòu)建左右子樹。三、停車場管理系統(tǒng)設(shè)計設(shè)計一個停車場管理系統(tǒng),支持車輛進(jìn)入、離開、查詢剩余車位、統(tǒng)計時間段內(nèi)車輛數(shù)功能。要求處理重復(fù)進(jìn)入、無效停車票等異常。功能說明:進(jìn)入:分配車位(編號遞增),記錄時間,返回停車票。離開:計算費(fèi)用(停留時間(小時)×5元,不足1小時按1小時),釋放車位。查詢:返回剩余車位數(shù)。統(tǒng)計:給定時間段,返回期間在場的車輛數(shù)。參考答案:```javaimportjava.time.LocalDateTime;importjava.time.temporal.ChronoUnit;importjava.util.concurrent.ConcurrentHashMap;importjava.util.concurrent.atomic.AtomicInteger;publicclassParkingLot{privatefinalinttotalSpots;privatefinalAtomicIntegeravailableSpots;privatefinalConcurrentHashMap<Integer,ParkingRecord>spotRecords;privatefinalConcurrentHashMap<String,Integer>licenseToSpot;privatefinalAtomicIntegernextSpot=newAtomicInteger(1);privatestaticfinalintPRICE_PER_HOUR=5;publicParkingLot(inttotalSpots){this.totalSpots=totalSpots;this.availableSpots=newAtomicInteger(totalSpots);this.spotRecords=newConcurrentHashMap<>();this.licenseToSpot=newConcurrentHashMap<>();}publicParkingTicketenter(Stringlicense){if(license==null||license.trim().isEmpty())thrownewIllegalArgumentException("車牌號為空");if(licenseToSpot.containsKey(license))thrownewIllegalArgumentException("車輛已在場");if(availableSpots.get()<=0)thrownewIllegalStateException("停車場已滿");intspot=nextSpot.getAndIncrement();if(spot>totalSpots)thrownewIllegalStateException("停車場已滿");LocalDateTimeenterTime=LocalDateTime.now();ParkingRecordrecord=newParkingRecord(license,enterTime,null);spotRecords.put(spot,record);licenseToSpot.put(license,spot);availableSpots.decrementAndGet();returnnewParkingTicket(spot,license,enterTime);}publicdoubleexit(ParkingTicketticket){if(ticket==null)thrownewIllegalArgumentException("停車票為空");ParkingRecordrecord=spotRecords.get(ticket.getSpotNumber());if(record==null||!record.license.equals(ticket.getLicense())||!record.enterTime.equals(ticket.getEnterTime())){thrownewIllegalArgumentException("無效停車票");}LocalDateTimeexitTime=LocalDateTime.now();record.exitTime=exitTime;longhours=ChronoUnit.HOURS.between(record.enterTime,exitTime);if(ChronoUnit.MINUTES.between(record.enterTime,exitTime)%60!=0)hours++;doublefee=hoursPRICE_PER_HOUR;spotRecords.remove(ticket.getSpotNumber());licenseToSpot.remove(record.license);availableSpots.incrementAndGet();returnfee;}publicintgetAvailableSpots(){returnavailableSpots.get();}publicintcountVehiclesInTimeRange(LocalDateTimestart,LocalDateTimeend){intcount=0;for(ParkingRecordrecord:spotRecords.values()){LocalDateTimeenter=record.enterTime;LocalDateTimeexit=record.exitTime==null?LocalDateTime.now():record.exitTime;if(enter.isBefore(end)&&exit.isAfter(start))count++;}returncount;}privatestaticclassParkingRecord{Stringlicense;LocalDateTimeenterTime;LocalDateTimeexitTime;ParkingRecord(Stringlicense,LocalDateTimeenterTime,LocalDateTimeexitTime){this.license=license;this.enterTime=enterTime;this.exitTime=exitTime;}}publicstaticclassParkingTicket{privatefinalintspotNumber;privatefinalStringlicense;privatefinalLocalDateTimeenterTime;publicParkingTicket(intspotNumber,Stringlicense,LocalDateTimeenterTime){this.spotNumber=spotNumber;this.license=license;this.enterTime=enterTime;}publicintgetSpotNumber(){returnspotNumber;}publicStringgetLicense(){returnlicense;}publicLocalDateTimegetEnterTime(){returnenterTime;}}}```解析:使用`ConcurrentHashMap`保證線程安全,`AtomicInteger`原子操作車位號和可用數(shù)。異常處理覆蓋重復(fù)進(jìn)入、無效票等場景,統(tǒng)計時考慮未離場車輛(`exitTime`為`null`)。四、多線程任務(wù)調(diào)度器實(shí)現(xiàn)多線程任務(wù)調(diào)度器,支持任務(wù)提交、狀態(tài)查詢,使用固定大小線程池(3個線程),記錄任務(wù)狀態(tài)(未開始、執(zhí)行中、已完成、失?。┘爱惓P畔?。參考答案:```javaimportjava.time.LocalDateTime;importjava.util.Map;importjava.util.UUID;importjava.util.concurrent.;publicclassTaskScheduler{privatefinalExecutorServicethreadPool;privatefinalMap<String,TaskInfo>taskMap;publicTaskScheduler(){this.threadPool=Executors.newFixedThreadPool(3);this.taskMap=newConcurrentHashMap<>();}publicStringsubmit(Runnabletask){StringtaskId=UUID.randomUUID().toString();TaskInfoinfo=newTaskInfo();info.state=TaskState.NOT_STARTED;taskMap.put(taskId,info);Future<?>future=threadPool.submit(()->{info.state=TaskState.RUNNING;try{task.run();info.state=TaskState.COMPLETED;info.finishTime=LocalDateTime.now();}catch(Exceptione){info.state=TaskState.FAILED;info.finishTime=LocalDateTime.now();info.exception=e;}});info.future=future;returntaskId;}publicTaskInfogetStatus(StringtaskId){returntaskMap.get(taskId);}publicvoidshutdown(){threadPool.shutdown();}publicenumTaskState{NOT_STARTED,RUNNING,COMPLETED,FAILED}publicstaticclassTaskInfo{TaskStatestate;LocalDateTimefinishTime;Exceptionexception;Future<?>future;publicTaskStategetState(){returnstate;}publicLocalDateTimegetFinishTime(){returnfinishTime;}publicExceptiongetException(){returnexception;}}}```解析:通過`ExecutorService`創(chuàng)建固定線程池,`Future`跟蹤任務(wù)執(zhí)行。任務(wù)信息存儲在`ConcurrentHashMap`中,狀態(tài)通過任務(wù)執(zhí)行過程更新,支持線程安全的狀態(tài)查詢。五、日志文件IP統(tǒng)計讀取大日志文件(每行格式:“IP時間操作”),統(tǒng)計各IP訪問次數(shù),結(jié)果按次數(shù)降序、次數(shù)相同則IP升序?qū)懭胛募⒖即鸢福篳``javaimportjava.io.;importjava.nio.charset.StandardCharsets;importjava.util.;importjava.util.stream.Collectors;publicclassLogIpAnalyzer{publicstaticvoidanalyzeAndWrite(StringinputPath,StringoutputPath){Map<String,Integer>ipCount=newHashMap<>();try(BufferedReaderreader=newBufferedReader(newInputStreamReader(newFileInputStream(inputPath),StandardCharsets.UTF_8))){Stringline;while((line=reader.readLine())!=null){String[]parts=line.split("",3);if(parts.length>=1){Stringip=parts[0];ipCount.put(ip,ipCount.getOrDefault(ip,0)+

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論